.net Microsoft.IdentityModel.Tokens:添加附加声明 背景
出于authn/z目的,我们正在使用创建JWT令牌。此令牌通过Authorize:BearerHTTP头传递到不同的微服务以模拟调用者 微服务本身利用Microsoft.IdentityModel.Tokens来验证JWT令牌:.net Microsoft.IdentityModel.Tokens:添加附加声明 背景,.net,asp.net-core,jwt,claims-based-identity,bearer-token,.net,Asp.net Core,Jwt,Claims Based Identity,Bearer Token,出于authn/z目的,我们正在使用创建JWT令牌。此令牌通过Authorize:BearerHTTP头传递到不同的微服务以模拟调用者 微服务本身利用Microsoft.IdentityModel.Tokens来验证JWT令牌: using System; using System.Text; using Microsoft.IdentityModel.Tokens; using Microsoft.AspNetCore.Builder; // The key length needs to
using System;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Builder;
// The key length needs to be of sufficient length, or otherwise an error will occur.
var tokenSecretKey = Encoding.UTF8.GetBytes(Configuration["TokenSecretKey"]);
var tokenValidationParameters = new TokenValidationParameters
{
// Token signature will be verified using a private key.
ValidateIssuerSigningKey = true,
RequireSignedTokens = true,
IssuerSigningKey = new SymmetricSecurityKey(tokenSecretKey),
// Token will only be valid if contains "accelist.com" for "iss" claim.
ValidateIssuer = true,
ValidIssuer = "accelist.com",
// Token will only be valid if contains "accelist.com" for "aud" claim.
ValidateAudience = true,
ValidAudience = "accelist.com",
// Token will only be valid if not expired yet, with 5 minutes clock skew.
ValidateLifetime = true,
RequireExpirationTime = true,
ClockSkew = new TimeSpan(0, 5, 0),
ValidateActor = false,
};
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
TokenValidationParameters = tokenValidationParameters,
});
某些JWT保留声明将自动填充到HttpContext.User中,即
问题 是否有一种简单而优雅的方法将其他自定义声明填充到HttpContext.User中?目前我能想到的唯一方法是解码令牌并调用HttpContext.User.Claims.Add(…)
提前谢谢你 不必解码令牌并添加您的
自定义声明
,您可以动态地对用户
和自定义
声明进行联合
:
private async Task<JwtSecurityToken> GetJwtSecurityToken(ApplicationUser user)
{
//Get the user claims
var userClaims = await _userManager.GetClaimsAsync(user);
//Merge the claims here
return new JwtSecurityToken(
issuer: "", //Insert your issuer
audience: "",//Insert your audience
claims: GetTokenClaims(user).Union(userClaims), //This is the Union you need
expires: DateTime.UtcNow.AddMinutes(5),//Add expiry time here
signingCredentials: new SigningCredentials(IssuerSigningKey, SecurityAlgorithms.HmacSha256)//Do your magic here
);
}
最后,您可以将其总结如下:
//Get the token combination
var token = await GetJwtSecurityToken(user);
//Write and return the token
return Ok(new
{
token = new JwtSecurityTokenHandler().WriteToken(token),
expiration = token.ValidTo,
});
您不需要解码令牌并添加您的
自定义声明
,而需要对用户
和自定义
声明进行动态的联合
:
private async Task<JwtSecurityToken> GetJwtSecurityToken(ApplicationUser user)
{
//Get the user claims
var userClaims = await _userManager.GetClaimsAsync(user);
//Merge the claims here
return new JwtSecurityToken(
issuer: "", //Insert your issuer
audience: "",//Insert your audience
claims: GetTokenClaims(user).Union(userClaims), //This is the Union you need
expires: DateTime.UtcNow.AddMinutes(5),//Add expiry time here
signingCredentials: new SigningCredentials(IssuerSigningKey, SecurityAlgorithms.HmacSha256)//Do your magic here
);
}
最后,您可以将其总结如下:
//Get the token combination
var token = await GetJwtSecurityToken(user);
//Write and return the token
return Ok(new
{
token = new JwtSecurityTokenHandler().WriteToken(token),
expiration = token.ValidTo,
});
嗨@Fabe,你试过我下面答案中的方法吗?嗨@Fabe,你试过我下面答案中的方法吗?非常感谢你的帮助!这不完全是我的意思。您正在描述如何向现有令牌添加其他声明。我已经将现有声明添加到JWT令牌中。当客户端接收到令牌时,一些JWT声明会自动填充到HttpContext.User中,但当我尝试访问其他JWT声明时,返回null。对不起,我没说清楚。我会更新我的问题。非常感谢你的帮助!这不完全是我的意思。您正在描述如何向现有令牌添加其他声明。我已经将现有声明添加到JWT令牌中。当客户端接收到令牌时,一些JWT声明会自动填充到HttpContext.User中,但当我尝试访问其他JWT声明时,返回null。对不起,我没说清楚。我会更新我的问题。