gpt4 book ai didi

c# - Asp Net Identity - 声明与自定义 IdentityUser

转载 作者:行者123 更新时间:2023-11-30 15:16:52 27 4
gpt4 key购买 nike

我对自定义用户配置文件以在应用程序中实现自定义逻辑的最佳方式感到困惑。

假设您必须使用这种属性来分析用户:

  • 等级
  • 可以处理
  • 可以离线工作
  • 可以发送邮件
  • canViewFullName

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

最佳答案

这两种方法都是可行的,有人可能会说这是一个偏好问题。

我会说在 IdentityUser 实现中只使用添加的属性更容易访问并且需要的代码也更少。

在性能方面,我认为需要添加的用户和数据越多,Properties 和数据库存储就越好,使用 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; }
}

然后您就可以非常轻松地访问 Controller 中的属性:

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

关于 claim 方式:

    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;

当然,如果需要,您可以将存储的属性分贝到声明中。使用上面的 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;
}

关于c# - Asp Net Identity - 声明与自定义 IdentityUser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48406747/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com