asp.net-core - 如何在 JWT 令牌中包含声明?
问题描述
嗨,我正在.Net 核心中开发 Web 应用程序。我已经实现了 V2 身份验证。现在我需要添加授权。该要求指出,首先,
收集用户的声明不应该是应用程序的工作,它们应该在用户的 JWT 中可用。其次,将根据声明授予应用程序的权限。
下面是我的验证码。
services
.AddAuthentication(o =>
{
o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(o =>
{
o.Authority = azureActiveDirectoryOptions.Authority;
o.TokenValidationParameters = new TokenValidationParameters
{
ValidAudiences = new List<string>
{
azureActiveDirectoryOptions.AppIdUri,
azureActiveDirectoryOptions.ClientId
},
};
});
services.AddMvc(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
有人可以帮我添加基于声明的授权吗?任何帮助将不胜感激。谢谢
解决方案
您可以使用以下代码在 JWT 令牌中添加自定义声明。
public string createToken()
{
var tokenHandler = new JwtSecurityTokenHandler();
//create a identity and add claims to the user which we want to log in
ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[]
{
new Claim("UserName", "joey"),
new Claim("Email","xxx@test.com")
});
const string sec = "yoursecurityKey";
var now = DateTime.UtcNow;
var securityKey = new SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));
var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
//create the jwt
var jwtSecurityToken = handler.CreateJwtSecurityToken(
"issuer",
"Audience",
new ClaimsIdentity(claimsIdentity),
DateTime.Now,
DateTime.Now.AddHours(1),
DateTime.Now,
signingCredentials);
var tokenString = tokenHandler.WriteToken(token);
return tokenString;
}
更多细节,你可以参考这篇文章。
更新:
如果是这样,您可以使用JwtBearerEvents添加声明。
.AddJwtBearer(o =>
{
//Additional config snipped
o.Events = new JwtBearerEvents
{
OnTokenValidated = async ctx =>
{
//Get the calling app client id that came from the token produced by Azure AD
string clientId = ctx.Principal.FindFirstValue("appid");
var claims = new List<Claim>
{
new Claim("UserName", "joey")
};
var appIdentity = new ClaimsIdentity(claims);
ctx.Principal.AddIdentity(appIdentity);
}
};
});
推荐阅读
- laravel - 如何在甜蜜警报和 laravel 中添加 2 个链接?
- ruby-on-rails - 使用 format.json 的 respond_to 找不到部分
- scala - Spark [Scala]:如何解决它:使用 MLWritable for Customized Estimator 和自定义参数打破序列化问题
- matlab - 通过端口句柄获取底层子系统输入/输出块
- html - 如何使用内部绝对 div 的所有宽度
- java - Centos 7 中的 PKIX 路径构建失败
- mongodb - 如何从 MongoDB 集合中收集特定样本?
- cordova - 如何使用cordova phonegap 条形码扫描仪从整数字符串生成(不扫描)UPC_A 条形码
- uwp - 如何控制 Windows ML 用于评估的线程数
- python - 将原始值与计算出最小二乘的值进行比较