Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/neo4j/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用ASP.NET标识3的自定义密码策略_C#_Asp.net_Asp.net Identity - Fatal编程技术网

C# 使用ASP.NET标识3的自定义密码策略

C# 使用ASP.NET标识3的自定义密码策略,c#,asp.net,asp.net-identity,C#,Asp.net,Asp.net Identity,Asp.NET identity 3删除了UserManager的单参数构造函数,因此在从UserManager继承时,我必须指定所有10个参数。由于我要完成的任务很简单,因此我编写了以下代码: public class AppUserManager : UserManager<ApplicationUser> { public AppUserManager() : base(new UserStore<ApplicationUser>(new AppDbCont

Asp.NET identity 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" }); }
        });
    }
}
公共类AppUserManager:UserManager
{
public AppUserManager():base(新用户存储(新AppDbContext()),null,null,null,新密码验证器[]{new PasswordValidator()},null,null,null,null,null)
{
}
}
公共类密码验证程序:IPasswordValidator
{
公共任务ValidateSync(UserManager、ApplicationUser用户、字符串密码)
{
返回任务。运行(()=>
{
如果(password.Length>=4)返回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;
        }
[HttpPost]
公共异步任务Post([FromBody]RegisterSchema req)
{
if(ModelState.IsValid)
{
var user=新的应用程序用户(请求用户名);
AppUserManager um=新的AppUserManager();
var result=wait um.CreateAsync(用户,请求密码);
返回结果;
}

result
始终为null(而
um
似乎正确)

这可能是因为您在构造函数中放置了太多null。以下是我用于UserManager重写的构造函数

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)
        {

        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Threading.Tasks;
使用Microsoft.AspNet.Http;
使用Microsoft.AspNet.Identity;
使用Microsoft.Extensions.Logging;
使用Microsoft.Extensions.OptionsModel;
命名空间[YourApp]。服务
{
公共类应用程序管理员:UserManager
{
公共应用程序服务器管理器(IUserStore存储、IOOptions访问器、IPasswordHasher密码hasher、,
IEnumerable用户验证程序,IEnumerable密码验证程序,
ILookupNormalizer键规范化器、IdentityErrorDescriptiber错误、IServiceProvider服务、ILogger logger、,
IHttpContextAccessor(上下文访问器)
:base(存储、选项访问器、密码哈希器、用户验证器、密码验证器、密钥规范化器、错误、服务、记录器、上下文访问器)
{
}
}
}

这可能是因为您在构造函数中放置了太多null。下面是我用于UserManager重写的构造函数

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)
        {

        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Threading.Tasks;
使用Microsoft.AspNet.Http;
使用Microsoft.AspNet.Identity;
使用Microsoft.Extensions.Logging;
使用Microsoft.Extensions.OptionsModel;
命名空间[YourApp]。服务
{
公共类应用程序管理员:UserManager
{
公共应用程序服务器管理器(IUserStore存储、IOOptions访问器、IPasswordHasher密码hasher、,
IEnumerable用户验证程序,IEnumerable密码验证程序,
ILookupNormalizer键规范化器、IdentityErrorDescriptiber错误、IServiceProvider服务、ILogger logger、,
IHttpContextAccessor(上下文访问器)
:base(存储、选项访问器、密码哈希器、用户验证器、密码验证器、密钥规范化器、错误、服务、记录器、上下文访问器)
{
}
}
}

前面的答案很有效。我为需要完整型号的用户附上我的版本:

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()
        };
    }       
}
公共类AppUserManager:UserManager
{
公共AppUserManager(IServiceProvider服务,IHttpContextAccessor contextAccessor,ILogger记录器):基本(新用户存储(新应用程序上下文()),新CustomOptions(),新PasswordHasher(),新用户验证程序[]{new UserValidator()},新密码验证程序[]{new PasswordValidator()},新UpperInvariantLookupNormalizer()),新的IdentityErrorDescriber(),服务,记录器,上下文访问器)
{
}
}
公共类密码验证程序:IPasswordValidator
{
公共任务ValidateSync(UserManager、ApplicationUser用户、字符串密码)
{
返回任务。运行(()=>
{
如果(password.Length>=4)返回IdentityResult.Success;
else{return IdentityResult.Failed(new IdentityError{Code=“SHORTPASSWORD”,Description=“Password too short”});}
});
}
}
公共类自定义选项:IOOptions
{
公共标识选项值{get;private set;}
公共服务选项()
{
值=新标识选项
{
ClaimsIdentity=新的ClaimsIdentityOptions(),
Cookies=新标识CookieOptions(),
锁定=新锁定选项(),
密码=null,
User=new UserOptions(),
SignIn=新的SignInOptions(),
令牌=新令牌选项()
};
}       
}
您可以在ConfigureServices()中插入服务:

services.addScope();

前面的答案很有效。我为需要完整型号的用户附上我的版本:

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()
        };
    }       
}
公共类AppUserManager:UserManager
{
公共AppUserManager(IServiceProvider服务,IHttpContextAccessor contextAccessor,ILogger记录器):基本(新用户存储(新应用程序上下文()),新CustomOptions(),新PasswordHasher(),新用户验证程序[]{new UserValidator()},新密码验证程序[]{new PasswordValidator()},新UpperInvariantLookupNormalizer()),新的IdentityErrorDescriber(),服务,记录器,上下文访问器)
{
}
}
公共类密码验证程序:IPasswordValidator
{
公共任务ValidateSync(UserManager、ApplicationUser用户、字符串密码)
{
返回任务。运行(()=>
{
如果(password.Length>=4)返回IdentityResult.Success;
else{返回Id