使用 ASP.NET 身份 3 的自定义密码策略



Asp.NET 标识 3 删除了 UserManager 的单参数构造函数,因此在从 UserManager 继承时,我必须指定所有 10 个参数。由于我必须完成的简单任务,我编写了以下代码:

public class AppUserManager : UserManager<ApplicationUser>
{
    public AppUserManager() : base(new UserStore<ApplicationUser>(new AppDbContext()), null, null, null, new PasswordValidator[] { new PasswordValidator() }, null, null, null, null, null)
    {
    }
}
public class PasswordValidator : IPasswordValidator<ApplicationUser>
{
    public Task<IdentityResult> ValidateAsync(UserManager<ApplicationUser> manager, ApplicationUser user, string password)
    {
        return Task.Run(() =>
        {
            if (password.Length >= 4) return IdentityResult.Success;
            else { return IdentityResult.Failed(new IdentityError { Code = "SHORTPASSWORD", Description = "Password too short" }); }
        });
    }
}

我想这不起作用,因为当我调用控制器时:

    [HttpPost]
    public async Task<dynamic> Post([FromBody] RegisterSchema req)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser(req.username);
            AppUserManager um = new AppUserManager();
            var result = await um.CreateAsync(user, req.password);
            return result;
        }

result始终为空(而um似乎是正确的)

这可能是因为你在构造函数中放置了太多的空值。 这是我用于用户管理器覆盖的构造函数。

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Identity;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel;
namespace [YourApp].Services
{
    public class ApplicationUserManager : UserManager<ApplicationUser>
    {
        public ApplicationUserManager(IUserStore<ApplicationUser> store, IOptions<IdentityOptions> optionsAccessor, IPasswordHasher<ApplicationUser> passwordHasher,
                                      IEnumerable<IUserValidator<ApplicationUser>> userValidators, IEnumerable<IPasswordValidator<ApplicationUser>> passwordValidators,
                                      ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, IServiceProvider services, ILogger<UserManager<ApplicationUser>> logger,
                                      IHttpContextAccessor contextAccessor)
        : base(store, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, logger, contextAccessor)
        {
        }
    }
}

前面的答案效果很好。我为需要完整模型的人附加我的版本:

public class AppUserManager : UserManager<ApplicationUser>
{
    public AppUserManager(IServiceProvider services, IHttpContextAccessor contextAccessor, ILogger<UserManager<ApplicationUser>> logger) : base(new UserStore<ApplicationUser>(new ApplicationDbContext()), new CustomOptions(), new PasswordHasher<ApplicationUser>(), new UserValidator<ApplicationUser>[] { new UserValidator<ApplicationUser>() }, new PasswordValidator[] { new PasswordValidator() }, new UpperInvariantLookupNormalizer(), new IdentityErrorDescriber(), services, logger, contextAccessor) 
    {
    }
}
public class PasswordValidator : IPasswordValidator<ApplicationUser>
{
    public Task<IdentityResult> ValidateAsync(UserManager<ApplicationUser> manager, ApplicationUser user, string password)
    {
        return Task.Run(() =>
        {
            if (password.Length >= 4) return IdentityResult.Success;
            else { return IdentityResult.Failed(new IdentityError { Code = "SHORTPASSWORD", Description = "Password too short" }); }
        });
    }
}
public class CustomOptions : IOptions<IdentityOptions>
{
    public IdentityOptions Value { get; private set; }
    public CustomOptions()
    {
        Value = new IdentityOptions
        {
            ClaimsIdentity = new ClaimsIdentityOptions(),
            Cookies = new IdentityCookieOptions(),
            Lockout = new LockoutOptions(),
            Password = null,
            User = new UserOptions(),
            SignIn = new SignInOptions(),
            Tokens = new TokenOptions()
        };
    }       
}

您可以在 ConfigureServices() 中注入服务:

        services.AddScoped<AppUserManager>();

相关内容

  • 没有找到相关文章

最新更新