一個JWT實際上就是一個字串,它由三部分組成,頭部(header)、載荷(Payload)與簽名。
Payload
payload中可以儲存使用者的資訊。
var claims = new Claim[]
{
new Claim(JwtRegisteredClaimNames.Sub, account),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Iat, now.ToUniversalTime().ToString(),
ClaimValueTypes.Integer64),
//使用者名稱
new Claim(ClaimTypes.Name,account),
//角色
new Claim(ClaimTypes.Role,”a”)
};
獲取所存放的account
var schemeProvider = context.RequestServices.GetService(typeof(IAuthenticationSchemeProvider)) as IAuthenticationSchemeProvider;
var defaultAuthenticate = await schemeProvider.GetDefaultAuthenticateSchemeAsync();
if (defaultAuthenticate != null)
{
var result = await context.AuthenticateAsync(defaultAuthenticate.Name);
var user = result?.Principal;
if (user != null)
{
account = user.Identity.Name;
}
}