【问题标题】:How to validate arbitrary conditions when authenticating an user?验证用户时如何验证任意条件?
【发布时间】:2020-07-31 19:00:23
【问题描述】:

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

【问题讨论】:

  • 嗨,@Léster,如果您有关于此问题的最新信息,请告诉我们。

标签: asp.net-core-mvc asp.net-core-identity


【解决方案1】:

对于您的情况,您可以创建自定义用户验证器。

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

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

这遵循 Identity 中的常见模式,您可以在其中实现接口(在本例中为 IValidator<T>)并提供所有验证代码,或者覆盖它的基本实现并通过覆盖方法添加额外的逻辑,就像我一样在这里做了。

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 开头的行之前的某处,添加以下行:

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

这会将CustomUserValidator 的实现添加到内部服务集合中,允许在需要IUserValidator&lt;ApplicationUser&gt; 的任何地方注入它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-20
    • 1970-01-01
    • 2020-04-26
    • 2015-06-19
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多