如何将IdentityServer4与ASP.NET Microsoft Identity的自定义密码验证一起使用

Cod*_*iot 3 c# asp.net validation asp.net-identity identityserver4

我正在使用IdentityServer4并使用ASP.NET身份,并且想要进行自定义密码验证,以便我可以为密码过期添加验证(例如,如果密码超过90天,则让用户更改密码等. ).

我在Startup.cs 的方法中.AddPasswordValidator<>设置时遇到了该方法,但是无法找到有关如何实现它的任何明确文档.services.AddIdentityConfigureServices()

任何人都可以帮助实现或指向一些类似的示例代码吗?(或者可能有助于了解我在哪里/如何使用IdentityServer4实现用户/密码的自定义验证)?

Dot*_*rog 9

我不认为密码验证器是你需要的,但是因为你问过 -
一个自定义密码验证器的例子(不是我的代码,链接到下面的文章):

public class SameCharacterPasswordValidator<TUser>: IPasswordValidator<TUser> 
       where TUser : class
{
    public Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, 
                                              TUser user, 
                                              string password)
    {
        return Task.FromResult(password.Distinct().Count() == 1 ? 
            IdentityResult.Failed(new IdentityError
            {
                Code = "SameChar",
                Description = "Passwords cannot be all the same character."
            }) : 
            IdentityResult.Success);
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以在ConfigureServices方法中应用自定义验证器

services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
    // Basic built in validations
    options.Password.RequireDigit = true;
    options.Password.RequireLowercase = true;
    options.Password.RequireNonLetterOrDigit = true;
    options.Password.RequireUppercase = true;
    options.Password.RequiredLength = 6;
})
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders()
    // Your custom validator here
    .AddPasswordValidator<SameCharacterPasswordValidator<ApplicationUser>>();
Run Code Online (Sandbox Code Playgroud)

这是一篇关于ASP.NET Identity的密码验证器的好文章:https: //elanderson.net/2016/03/asp-net-core-password-options-and-custom-validators/

请注意,密码验证器旨在检查密码是否符合您希望的格式(类似于正则表达式).因此,密码到期与它无关.这是密码的元数据,与密码的格式无关.
对于该用例,您可以向AspNetUsers表中添加一个字段(您可以通过扩展继承自IdentityUser(可能称为ApplicationUser)PasswordChangedAtDate字段的类来完成它.
然后,每次用户登录时都应该检查该验证你自己.

PS: .要认识到密码的强度或任何有做与用户存储实际上已经没有任何关系是很重要的IdentityServer IdentityServer作为您的STS(安全令牌服务),
我花了一些时间来实现它自己,这就是我认为值得一提的原因,尽管这对你来说可能是显而易见的.