C# 如何将自定义登录和角色mechanizm添加到asp mvc 5?
我不得不承认。即使在阅读了很多关于这个新MVC5身份的教程和所有owin的东西之后,我还是无法理解它。 我的任务是实现Stormpath(Stormpath.com)的登录和角色列表,它基本上是一个用户和组的web商店。我创建了一个服务,该服务根据stormpath对用户和密码进行身份验证,并返回分配给用户的角色/组 我还访问了ApplicationSignenManager,它默认情况下是使用Visual Studio中的新mvc项目创建的,并用以下内容替换主体:C# 如何将自定义登录和角色mechanizm添加到asp mvc 5?,c#,asp.net-mvc,asp.net-identity,C#,Asp.net Mvc,Asp.net Identity,我不得不承认。即使在阅读了很多关于这个新MVC5身份的教程和所有owin的东西之后,我还是无法理解它。 我的任务是实现Stormpath(Stormpath.com)的登录和角色列表,它基本上是一个用户和组的web商店。我创建了一个服务,该服务根据stormpath对用户和密码进行身份验证,并返回分配给用户的角色/组 我还访问了ApplicationSignenManager,它默认情况下是使用Visual Studio中的新mvc项目创建的,并用以下内容替换主体: public overrid
public override Task<SignInStatus> PasswordSignInAsync(string userName, string password, bool isPersistent, bool shouldLockout) {
return Task.Run(() =>
new StormpathService(new Configuration()).AuthenticateUser(userName, password) != null ? SignInStatus.Success : SignInStatus.Failure);
}
public override Task PasswordSignInAsync(字符串用户名、字符串密码、bool ispersist、bool shouldllockout){
返回任务。运行(()=>
新的StormpathService(新配置()).AuthenticateUser(用户名、密码)!=null?登录状态。成功:登录状态。失败);
}
当用户在页面的登录表单中输入数据时,事情就过去了,但在这之后,应用程序仍然认为我没有登录
asp mvc Identity mechanizm还需要做些什么才能尊重用户身份验证和角色管理的自定义方式?这是支持从Stormpath登录的最低要求
public class ApplicationUser : IUser {
public string ClientKey { get; set; }
public string Id { get; set; }
public string UserName { get; set; }
public string NewsFilter { get; set; }
public string FullName { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) {
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
public class StormpathUserStore : IUserStore<ApplicationUser>, IUserRoleStore<ApplicationUser> {
private readonly IStormpathService _stormpathService;
public StormpathUserStore(IStormpathService stormpathService) {
if (stormpathService == null) {
throw new ArgumentNullException("stormpathService");
}
_stormpathService = stormpathService;
}
public Task AddToRoleAsync(ApplicationUser user, string roleName) {
throw new NotImplementedException();
}
public Task RemoveFromRoleAsync(ApplicationUser user, string roleName) {
throw new NotImplementedException();
}
public Task<IList<string>> GetRolesAsync(ApplicationUser user) {
var groups = _stormpathService.GetUserGroups(_stormpathService.GetUserUrlFromId(user.Id));
return Task.FromResult(groups.ToArray() as IList<string>);
}
public Task<bool> IsInRoleAsync(ApplicationUser user, string roleName) {
#if DEBUG
var configuration = ObjectFactory.GetInstance<IConfiguration>();
if (!string.IsNullOrWhiteSpace(configuration.DebugUser)) {
return Task.FromResult(configuration.DebugRoles.Split(',').Contains(roleName));
}
#endif
var isInGroup =
_stormpathService.GetUserGroups(_stormpathService.GetUserUrlFromId(user.Id)).Contains(roleName);
return Task.FromResult(isInGroup);
}
public void Dispose() {
}
public Task CreateAsync(ApplicationUser user) {
throw new NotImplementedException();
}
public Task UpdateAsync(ApplicationUser user) {
throw new NotImplementedException();
}
public Task DeleteAsync(ApplicationUser user) {
throw new NotImplementedException();
}
public Task<ApplicationUser> FindByIdAsync(string userId) {
var userData = _stormpathService.GetUser(_stormpathService.GetUserUrlFromId(userId));
if (userData == null) {
return Task.FromResult((ApplicationUser)null);
}
var user = new ApplicationUser {
UserName = userData.UserName,
Id = userId,
ClientKey = userData.ClientId,
NewsFilter = userData.NewsFilter,
FullName = userData.FullName,
};
return Task.FromResult(user);
}
public Task<ApplicationUser> FindByNameAsync(string userName) {
throw new NotImplementedException();
}
}
// Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
public class ApplicationUserManager : UserManager<ApplicationUser> {
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store) {
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options,
IOwinContext context) {
var manager =
new ApplicationUserManager(new StormpathUserStore(ObjectFactory.GetInstance<IStormpathService>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser>(manager) {
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator {
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true
};
// Configure user lockout defaults
manager.UserLockoutEnabledByDefault = true;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 15;
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null) {
manager.UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity")) {TokenLifespan = TimeSpan.FromDays(14.0)};
}
return manager;
}
}
// Configure the application sign-in manager which is used in this application.
public class ApplicationSignInManager : SignInManager<ApplicationUser, string> {
public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
: base(userManager, authenticationManager) {
}
public override Task<SignInStatus> PasswordSignInAsync(string userName, string password, bool isPersistent,
bool shouldLockout) {
return Task.FromResult(
new StormpathService(new Configuration()).AuthenticateUser(userName, password) != null
? SignInStatus.Success
: SignInStatus.Failure);
}
public override Task SignInAsync(ApplicationUser user, bool isPersistent, bool rememberBrowser) {
return base.SignInAsync(user, true, rememberBrowser);
}
public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user) {
var result = user.GenerateUserIdentityAsync((ApplicationUserManager) UserManager).Result;
return Task.FromResult(result);
}
public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options,
IOwinContext context) {
return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
}
}
公共类应用程序用户:IUser{
公共字符串ClientKey{get;set;}
公共字符串Id{get;set;}
公共字符串用户名{get;set;}
公共字符串新闻筛选器{get;set;}
公共字符串全名{get;set;}
公共异步任务GenerateUserIdentityAsync(用户管理器){
//注意authenticationType必须与CookieAuthenticationOptions.authenticationType中定义的类型匹配
var userIdentity=wait manager.CreateIdentityAsync(这是DefaultAuthenticationTypes.ApplicationOkie);
//在此处添加自定义用户声明
返回用户身份;
}
}
公共类StormpathUserStore:IUserStore、IUserRoleStore{
专用只读IStormpathService\u stormpathService;
公共StormpathUserStore(IStormpathService stormpathService){
if(stormpathService==null){
抛出新的ArgumentNullException(“stormpathService”);
}
_stormpathService=stormpathService;
}
公共任务AddToRoleAsync(ApplicationUser用户,字符串roleName){
抛出新的NotImplementedException();
}
公共任务RemoveFromRoleAsync(应用程序用户,字符串roleName){
抛出新的NotImplementedException();
}
公共任务GetRolesAsync(应用程序用户用户){
var groups=_stormpathService.GetUserGroups(_stormpathService.GetUserUrlFromId(user.Id));
返回Task.FromResult(groups.ToArray()作为IList);
}
公共任务IsInRoleAsync(ApplicationUser用户,字符串roleName){
#如果调试
var配置=ObjectFactory.GetInstance();
如果(!string.IsNullOrWhiteSpace(configuration.DebugUser)){
返回Task.FromResult(configuration.DebugRoles.Split(',).Contains(roleName));
}
#恩迪夫
var IsingGroup=
_stormpathService.GetUserGroups(_stormpathService.GetUserUrlFromId(user.Id)).Contains(roleName);
返回Task.FromResult(ISingGroup);
}
公共空间处置(){
}
公共任务CreateAsync(ApplicationUser用户){
抛出新的NotImplementedException();
}
公共任务更新同步(ApplicationUser用户){
抛出新的NotImplementedException();
}
公共任务DeleteAsync(ApplicationUser用户){
抛出新的NotImplementedException();
}
公共任务FindByIdAsync(字符串用户ID){
var userData=_stormpathService.GetUser(_stormpathService.GetUserUrlFromId(userId));
if(userData==null){
返回Task.FromResult((ApplicationUser)null);
}
var user=新应用程序用户{
UserName=userData.UserName,
Id=用户Id,
ClientKey=userData.ClientId,
NewsFilter=userData.NewsFilter,
FullName=userData.FullName,
};
返回Task.FromResult(用户);
}
公共任务FindByNameAsync(字符串用户名){
抛出新的NotImplementedException();
}
}
//配置此应用程序中使用的应用程序用户管理器。UserManager在ASP.NET标识中定义,并由应用程序使用。
公共类应用程序管理员:UserManager{
公共应用程序服务器管理器(IUserStore存储)
:基地(商店){
}
公共静态应用程序SerManager创建(IdentityFactoryOptions选项,
IOwinContext(上下文){
风险值管理器=
新的ApplicationUserManager(新的StormpathUserStore(ObjectFactory.GetInstance());
//为用户名配置验证逻辑
manager.UserValidator=新的UserValidator(管理器){
AllowOnlyAlphanumericUserNames=false,
RequireUniqueEmail=true
};
//配置密码的验证逻辑
manager.PasswordValidator=新密码验证器{
所需长度=6,
RequiredOnletterDigit=真,
RequireDigit=true,
RequireLowercase=true,
RequireUppercase=true
};
//配置用户锁定默认值
manager.UserLockoutEnabledByDefault=true;
manager.DefaultAccountLockoutTimeSpan=TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout=15;
var dataProtectionProvider=options.dataProtectionProvider;
if(dataProtectionProvider!=null){
manager.UserTokenProvider=