验证用户身份时如何验证任意条件? [英] How to validate arbitrary conditions when authenticating an user?

查看:72
本文介绍了验证用户身份时如何验证任意条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个ASP.NET MVC Core应用程序,并且我想在允许身份验证时验证某些自定义条件.例如,提供有效凭据对但被应用程序管理员禁用的用户,或指示该用户最新付款信息的标记,或任何其他任意条件.在ASP.NET Core Identity中是否可以挂接此自定义验证的地方?我必须将此工作用于本地和外部身份验证.

Let's say I have an ASP.NET MVC Core application, and I want to validate certain custom conditions when allowing authentication. For example, an user that provides a valid pair of credentials, but is disabled by the application's administrator, or a flag that indicates the user is up-to-date with his payments, or any other arbitrary condition. Is there a place in ASP.NET Core Identity where I can hook this custom validation? I have to make this work for local and external authentication.

推荐答案

对于您而言,您可以创建自定义用户验证器.

For you case, you could create custom user validators.

为ASP.NET Core身份编写自定义验证器

Writing a custom validator for ASP.NET Core Identity

需要电子邮件地址以@ example.com结尾的自定义用户验证器

这遵循Identity中的通用模式,您可以在其中实现接口(在本例中为 IValidator< T> )并提供所有验证代码,或者覆盖该接口的基本实现,并且像我在这里一样通过覆盖方法添加其他逻辑.

This follows a common pattern within Identity, where you can either implement the interface (in this case IValidator<T>) and provide all of the validation code, or override the base implementation of it and add additional logic by overriding methods as I did here.

public class CustomUserValidator : UserValidator<ApplicationUser>
{
  public override async Task<IdentityResult> ValidateAsync(UserManager<ApplicationUser> manager, 
    ApplicationUser user)
  {
    IdentityResult baseResult = await base.ValidateAsync(manager, user);
    List<IdentityError> errors = new List<IdentityError>(baseResult.Errors);

    if (!user.Email.EndsWith("@example.com"))
    {
      IdentityError invalidEmailError = Describer.InvalidEmail(user.Email);
      invalidEmailError.Description += " Email address must end with @example.com";
      errors.Add(invalidEmailError);
    }

    return errors.Count > 0 ? IdentityResult.Failed(errors.ToArray()) : IdentityResult.Success;
  }
}

然后将其插入,转到Startup.cs文件并找到 ConfigureServices 方法.在以 services.AddIdentity 开头的行之前的某处,添加以下行:

Then to plug this in, head over to the Startup.cs file and find the ConfigureServices method. Somewhere before the line starting with services.AddIdentity, add the following line:

services.AddTransient<IUserValidator<ApplicationUser>, CustomUserValidator>();

这会将 CustomUserValidator 的实现添加到内部服务集合中,从而允许将其注入需要 IUserValidator< ApplicationUser> 的任何地方.

This will add the implementation of CustomUserValidator to the internal services collection, allowing it to be injected anywhere that an IUserValidator<ApplicationUser> is required.

这篇关于验证用户身份时如何验证任意条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆