我正在.NET Core 3.1中创建一个包含一些自定义声明的JWT令牌,
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.Security.Jwt.SecretKey));
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(CustomClaimTypes.TenantId, user.TenantId.ToString()),
new Claim(JwtRegisteredClaimNames.Sub, user.Email),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToUnixEpochDate().ToString(), ClaimValueTypes.Integer64)
};
var jwt = new JwtSecurityToken(
issuer: Configuration.Security.Jwt.Issuer,
audience: Configuration.Security.Jwt.Audience,
claims: claims,
notBefore: DateTime.UtcNow,
expires: DateTime.UtcNow.Add(Configuration.Security.Jwt.Expiration),
signingCredentials: new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256)
);
var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
我正在Startup.cs
中设置JWT,如下所示:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.SaveToken = true;
options.ClaimsIssuer = Configuration.Security.Jwt.Issuer;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
RequireExpirationTime = false,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration.Security.Jwt.Issuer,
ValidAudience = Configuration.Security.Jwt.Audience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.Security.Jwt.SecretKey)),
ClockSkew = TimeSpan.Zero
};
});
但是,当我尝试通过IHttpContextAccessor.HttpContext.User.Claims
访问声明时。我只看到:
[0] = {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier: b88ac068-9d05-4287-94e1-103ba86fd974}
[1] = {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name: demo@demo.com}
[2] = {AspNet.Identity.SecurityStamp: TYI7T2BMGQWQUIFXKVBARPWADTFJ7CEH}
[3] = {amr: pwd}
普通身份验证似乎可以正常工作,我可以访问用[Authorize]
装饰的操作,只是显示自定义声明。