Dar*_*oN1 4 c# attributes claims asp.net-identity
我对自定义用户配置文件以在应用程序中实现自定义逻辑的最佳方法感到有点困惑。
假设您必须使用此类属性来分析用户:
我必须在哪里实现这种属性?我是否必须自定义 IdentityUser(使用 ApplicationUser)还是必须创建自定义声明?
小智 5
两种方法都是可行的,人们可能会认为这是一个偏好问题。
我想说的是,仅在 IdentityUser 实现中使用添加的属性更容易访问,并且需要的代码也更少。
性能方面,我认为需要添加的用户和数据越多,属性就越好,因此数据库存储有意义,使用 cookie 可以更快,但取决于大量数据的使用和服务器配置,特别是如果您从长远来看,希望为每个用户存储大量信息可以证明更好。
您还必须考虑数据持久性,如果满足以下条件之一,则必须使用属性。
之后,这实际上取决于您的应用程序的品味和具体需求。
考虑到您的示例,您只能使用 IdentityUser 属性:
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity>GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
//There you can use display name or any attributes like a regular Model.
public LevelEnum Level { get; set; }
[Display(Name = "Is allowed to process")]
public bool CanProcess { get; set; }
public bool CanWorkOffline { get; set; }
public bool CanSendEmail { get; set; }
public bool CanViewFullName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后您可以非常轻松地访问控制器中的属性:
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
viewModel.Level = user.Level;
Run Code Online (Sandbox Code Playgroud)
同样的方法设置
user.Level = viewModel.Level;
Run Code Online (Sandbox Code Playgroud)
并使用 UserManager 保存用户:
await _userManager.UpdateAsync(user);
//or to create
await UserManager.CreateAsync(user, model.Password);
Run Code Online (Sandbox Code Playgroud)
至于索赔方式:
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
userIdentity.AddClaim(new Claim("Level", LevelEnum.Default));
return userIdentity;
}
Run Code Online (Sandbox Code Playgroud)
然后访问:
//claim can be null.
var claim = ((ClaimsIdentity)identity).FirstOrDefault("Level") ?? LevelEnum.Default;
Run Code Online (Sandbox Code Playgroud)
当然,如果需要,您可以将存储的属性存储到声明中。使用上面的属性示例:
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
userIdentity.AddClaim(new Claim(nameof(Level), Level));
return userIdentity;
}
Run Code Online (Sandbox Code Playgroud)