2015-06-10 28 views
0

有一个用户类,它具有名为“Avatar”的字段,用于存储他的个人资料图片的路径。我想在部分视图中的标题中显示它。所以我希望为用户身份添加声明。我把这个代码行我IdentityConfig.cs类中:添加自定义用户声明的适当位置

public override Task<ClaimsIdentity> CreateUserIdentityAsync(AppUser user) 
     { 
      if(!System.String.IsNullOrEmpty(user.Avatar)) 
       user.Claims.Add(new AppUserClaim() { ClaimType = "avatar", ClaimValue = user.Avatar}); 

      return user.GenerateUserIdentityAsync((AppUserManager)UserManager); 
     } 

但有一个问题:这要求在一段时间内(aprox的1小时)后消失,也没有显示头像。我发现,框架每隔30分钟重新生成一次用户的身份(默认)。并根据此:

regenerateIdentityCallback: (manager, user) => 
          user.GenerateUserIdentityAsync(manager) 

它调用GenerateUserIdentityAsync用户类的方法。在这种情况下,我不明白。有两个,在第一视线,生成用户身份的类似的方法:

  1. 内部APPUSER类,这需要usermanager类作为参数 - public async Task<ClaimsIdentity> GenerateUserIdentityAsync(AppUserManager manager)
  2. 内部SignInManager - public override Task<ClaimsIdentity> CreateUserIdentityAsync(AppUser user)

这是什么目的?哪里使用了每种方法?我应该使用哪一个来添加自定义用户声明?

回答

2

我重构了一个标准的ASP.NET MVC项目,所以我不重复添加声明的代码。

Startup.Auth.cs:

public void ConfigureAuth(IAppBuilder app, Container container) 
{ 
    app.UseCookieAuthentication(new CookieAuthenticationOptions 
    { 
     Provider = new CookieAuthenticationProvider 
     { 
      OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, User>(
       validateInterval: TimeSpan.FromMinutes(30), 
       regenerateIdentity: (manager, user) => IdentityHelper.GenerateUserIdentityAsync(user, manager)) 
     } 
    }); 
} 

然后我做了一个静态辅助方法来生成身份:

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(User user, UserManager<User> manager) 
{ 
    var userIdentity = await manager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie).ConfigureAwait(false); 

    userIdentity.AddClaim(new Claim("Key", "Value")); 

    return userIdentity; 
} 

现在,您将能够从您的SignInManager重用这个助手。

public class ApplicationSignInManager : SignInManager<User, string> 
{ 
    public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager) 
     : base(userManager, authenticationManager) 
    { 
    } 

    public override Task<ClaimsIdentity> CreateUserIdentityAsync(User user) 
    { 
     return IdentityHelper.GenerateUserIdentityHelperAsync(user, (ApplicationUserManager)UserManager); 
    } 
} 
相关问题