我正在尝试创建继承自Microsoft.AspNet.Identity
的基于角色的安全性,如果需要,只需更改CustomUser类即可与许多不同的数据库一起使用。我不希望通过实体框架创建5个表。
我创建了一个虚拟项目,其中包含了所有代码,并且一直试图通过这样做来了解安全性的工作原理。
我仍然坚持CustomUserManager
以及如何在帐户控制器中运行 - 在预建项目中似乎有很多我不想要的东西,如下所示:< / p>
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
以上是否真的有必要,我希望第一部分只是作为基于角色的安全性使用我自己的密码来实现。
有人能给我一些关于如何实现这个目标的指示吗?
我的代码:
startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentity<CustomUser, CustomUserRole>();
// tell the application to add mvc
services.AddMvc();
}
自定义身份代码
public class CustomUserManager : UserManager<CustomUserRole>
{
public CustomUserManager(IUserStore<CustomUserRole> store, IOptions<IdentityOptions> optionsAccessor, IPasswordHasher<CustomUserRole> passwordHasher, IEnumerable<IUserValidator<CustomUserRole>> userValidators, IEnumerable<IPasswordValidator<CustomUserRole>> passwordValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, IServiceProvider services, ILogger<UserManager<CustomUserRole>> logger, IHttpContextAccessor contextAccessor) : base(store, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, logger, contextAccessor)
{
}
}
public class CustomUser
{
public Guid Id { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string SecurityStamp { get; set; }
public string PasswordHash { get; set; }
}
public class CustomUserStore : IUserStore<CustomUser>
{
private readonly string connectionString;
public CustomUserStore(string connectionString)
{
this.connectionString = connectionString;
}
public CustomUserStore()
{
connectionString = ConfigurationManager.ConnectionStrings[""].ConnectionString;
}
public void Dispose()
{
}
public Task<IdentityResult> CreateAsync(CustomUser user, CancellationToken cancellationToken)
{
user.PasswordHash = PasswordStorage.CreateHash(user.PasswordHash);
Task.Factory.StartNew(() =>
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (var cmd = new SqlCommand("CreateUser", connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@username", user.UserName);
cmd.Parameters.AddWithValue("@password", user.PasswordHash);
cmd.ExecuteNonQuery();
}
}
});
throw new NotImplementedException();
}
// all other methods are similar but removed for brevity sake
}
public class CustomUserRole { }
public class CustomUserRoleStore : IRoleStore<CustomUserRole>
{
public Task<IdentityResult> CreateAsync(CustomUserRole role, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
// all the other methods are the same as I'm not sure what to put in them, if anything
}