Asp Net Identity - 声明与自定义IdentityUser

时间:2018-01-23 16:39:23

标签: c# attributes asp.net-identity claims

我对自定义用户配置文件的最佳方法有点困惑,以便在应用程序中实现自定义逻辑。

假设您必须使用这种属性来描述用户:

  • 等级
  • canProcess
  • canWorkOffline
  • canSendEmail
  • canViewFullName

我在哪里必须实现这种属性? 我是否必须自定义IdentityUser(使用ApplicationUser)还是必须创建自定义声明?

1 个答案:

答案 0 :(得分:3)

这两种方法都是可行的,人们可以认为这是一个偏好问题。

我想说在IdentityUser实现中只使用添加的proprerties更容易访问,并且需要更少的代码。

性能方面,我认为需要添加的用户和数据越多,Proprerties就越好,因此DB存储有意义,使用cookie可以更快,但是对大量数据的使用和服务器配置进行了分离特别是如果你想为每个用户存储大量信息,从长远来看可以更好。

您还必须考虑数据持久性 如果以下情况属实,则必须使用Proprerties。

  • 数据需要无限期存储
  • 如果用户未登录,则可以或必须访问数据。

在那之后,这真的是你的应用中的品味和特殊需求。

考虑到您的示例,您只能使用IdentityUser proprerties:

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

然后你可以很容易地访问控制器中的属性:

var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
viewModel.Level = user.Level;

设置

的方式相同
user.Level = viewModel.Level;

使用UserManager保存用户:

await _userManager.UpdateAsync(user);
//or to create
await UserManager.CreateAsync(user, model.Password);

至于索赔方法:

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

然后访问:

//claim can be null.
var claim = ((ClaimsIdentity)identity).FirstOrDefault("Level") ?? LevelEnum.Default;

当然,如果需要,您可以将存储的属性db分配给声明。 使用上面的Propreties示例:

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