我想生成一个Jwt令牌,然后再验证它。
创建令牌:
var user = await this._applicationUserProvider.GetCurrentUserAsync();
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.NameId, user.Id),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_appSettings.Token.Key));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(this._appSettings.Token.Issuer,
this._appSettings.Token.Issuer,
claims,
expires: DateTime.Now.AddMinutes(this._appSettings.Token.DownloadTokenExpireMin),
signingCredentials: creds);
稍后,我想要验证此令牌:
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_appSettings.Token.Key));
TokenValidationParameters validationParameters =
new TokenValidationParameters
{
ValidIssuer = this._appSettings.Token.Issuer,
ValidAudiences = new[] { this._appSettings.Token.Issuer },
IssuerSigningKeys = new[] { key }
};
// Now validate the token. If the token is not valid for any reason, an exception will be thrown by the method
SecurityToken validatedToken;
JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
var user = handler.ValidateToken(token, validationParameters, out validatedToken);
这是一个错误:Jwt没有很好地形成。
在搜索时,我发现:https://github.com/aspnet/Security/issues/1332基本上说Jwt没有加密。
但是,我无法弄清楚如何在签名后加密令牌。
答案 0 :(得分:2)
JwtSecurityTokenHandler.ValidateToken()
期望紧凑序列化格式的标记字符串。因此,在构建JwtSecurityToken
的实例之后,您应该以紧凑格式将其序列化为JWT。
你可以通过JwtSecurityTokenHandler.WriteToken()
来电:
var token = new JwtSecurityToken(this._appSettings.Token.Issuer,
this._appSettings.Token.Issuer,
claims,
expires: DateTime.Now.AddMinutes(this._appSettings.Token.DownloadTokenExpireMin),
signingCredentials: creds);
var tokenHandler = new JwtSecurityTokenHandler();
string tokenSerialized = tokenHandler.WriteToken(token);
结果你得到一个像
这样的字符串eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJTb21lIFVzZXIiLCJuYW1laWQiOiIxMjMiLCJqdGkiOiIzMTQ3YWJmOC05MWYzLTRhZmItYjYyYi03MzZlZDJhNTg3ZjQiLCJleHAiOjE1MjI4MjUwNTYsImlzcyI6IlNvbWUgSXNzdWVyIiwiYXVkIjoiU29tZSBJc3N1ZXIifQ.RD0NntbPWBZUyyayB6SRmNzBPuZ86c30btLbSmhPUmo
可以由JwtSecurityTokenHandler.ValidateToken()
成功验证。
答案 1 :(得分:0)
ChiragMS-
我正在处理加密/解密jwt令牌的同一问题。根据我的研究,可以使用身份验证事件来实现。例如使用OIDC:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = "OpenIdConnect";
}).AddCookie(options =>
{
options.Events = new CookieAuthenticationEvents()
{
//commented out for brevity
};
})
.AddOpenIdConnect(options =>
{
//commented out for brevity
options.Events = new OpenIdConnectEvents
{
OnTokenResponseReceived = context =>
{
var decryptedContent = YourCryptograpy.Decrypt(context.HttpContext);
return Task.CompletedTask;
},
};
}
);