【发布时间】:2019-12-18 12:36:42
【问题描述】:
我正在使用 Identity 开发 .NET Core MVC 项目。我目前有一个正常的基于 cookie 的身份验证的工作项目,摘自 Identity config:
public class IdentityHostingStartup : IHostingStartup
{
public void Configure(IWebHostBuilder builder)
{
builder.ConfigureServices((context, services) => {
services.AddDbContext<TauManagerIdentityDbContext>(options =>
options.UseNpgsql(
context.Configuration.GetConnectionString("TauManagerIdentityDbContextConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddRoles<IdentityRole>()
.AddRoleManager<ApplicationRoleManager>()
.AddEntityFrameworkStores<TauManagerIdentityDbContext>()
.AddUserManager<ApplicationIdentityUserManager>()
.AddDefaultUI()
.AddDefaultTokenProviders();
});
}
}
我正在使用AuthorizeAttribute 来控制不同角色对我的网络应用程序中不同操作的访问。
现在我面临的情况是,我必须仅对一项特定操作使用某种基于令牌的身份验证。我在 SO 上阅读了几篇关于使用 .NET Core Identity 设置 JWT 的文章和问题,我发现最接近我的案例的是 Using Identity with token and cookie authentication。
但是,我有两个问题:
- 这确实是为此类场景生成身份验证令牌的最简单方法吗?
- 到目前为止,我看到的所有 JWT 示例都包含对用户电子邮件的引用,例如生成令牌时将
new Claim(JwtRegisteredClaimNames.Sub, user.Email)添加到声明列表中。我根本不收集用户的电子邮件,这是我想保留的深思熟虑的决定。有什么方法可以使用例如代替用户名?
提前致谢!
【问题讨论】:
-
JWT 的子令牌就是任何用户标识符。如果您的用户名是唯一的,您可以使用它们,或者使用他们的数据库主键,或者为此目的为您的数据库中的每个用户提供一个随机 GUID。
标签: c# authentication asp.net-core-mvc jwt asp.net-identity