2015-06-19 35 views
0

我不得不承認。即使閱讀了很多關於這個新的mvc 5 Identity以及所有owin的東西的教程,我都無法想象它。 我的任務是從Stormpath(Stormpath.com)實現登錄和角色列表,這是一個基本上面向用戶和組的網絡商店。我創建了一個服務,用於根據stormpath驗證用戶&密碼並返回分配給用戶的角色/組。如何添加自定義登錄和角色mechanizm到asp mvc 5?

我也去了那個默認情況下在Visual Studio中的一個新的MVC項目創建和替代身體ApplicationSignInManager:

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

} 

事情經過,當用戶輸入數據到登錄表單OA頁面,但在此之後,應用程序仍然認爲我沒有登錄。

還有什麼需要做的asp mvc身份mechanizm尊重自定義的身份驗證方式的用戶和角色管理?

回答

0

這是我必須支持從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); 
     } 
    } 
相關問題