我尝试在 C# asp.net core mvc 项目中应用 jwt 生成器。我可以创建 jwt 令牌并将其用于登录站点。但是看着 jwt 实例,我感到困惑,我不确定我的工作是否是 jwt 的最佳实践。这是我的代码;
这个 JwtHandler 接受 tokenoptions 类并声明然后生成令牌
public static class JwtHandler
{
public static TokenOptions TokenOptions { get; set; }
public static OperationResult<string> GenerateToken(IEnumerable<Claim> claims)
{
OperationResult<string> result = new();
if (TokenOptions == null)
{
result.Messages = "Token Options cannot be null."));
result.IsSuccess = false;
return result;
}
SymmetricSecurityKey secretKey = new(Encoding.UTF8.GetBytes(TokenOptions.SecretKey));
SigningCredentials signingCredentials = new(secretKey, SecurityAlgorithms.HmacSha256Signature);
JwtSecurityToken jwt = new
(
issuer: TokenOptions.Issuer,
audience: TokenOptions.Audience,
expires: DateTime.Now.AddMinutes(TokenOptions.TokenExpirationInMinutes),
notBefore: DateTime.Now,
claims: claims,
signingCredentials: signingCredentials
);
result.Data = new JwtSecurityTokenHandler().WriteToken(jwt);
return result;
}}
Tokenoptions.cs
public class TokenOptions
{
public string Audience { get; set; }
public string Issuer { get; set; }
public int TokenExpirationInMinutes { get; set; }
public string SecretKey { get; set; }
}
这是我的startup.cs
services.AddAuthentication()
.AddCookie(c =>
{
c.LoginPath = new PathString("/login");
c.LogoutPath = new PathString("/logout");
})
.AddCustomJwtBearer(Configuration);
自定义JwtBearer
public static void AddCustomJwtBearer(this AuthenticationBuilder builder, IConfiguration configuration)
{
TokenOptions tokenOptions = configuration.GetSection("TokenOptions").Get<TokenOptions>();
JwtHandler.TokenOptions = tokenOptions;
builder.AddJwtBearer(c =>
{
c.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidIssuer = tokenOptions.Issuer,
ValidAudience = tokenOptions.Audience,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOptions.SecretKey))
};
});
}
这是我调用 jwthandler 的方法
[HttpPost("/token")]
public async Task<IActionResult> TokenGenerate([FromBody] UserModel userModel)
{
OperationResult<User> userResult = await _userService.LoginAsync(userModel.EmailAddress, userModel.Password);
if (!userResult.IsSuccess)
{
return BadRequest(userResult);
}
List<Claim> claims = new()
{
new Claim(ClaimTypes.Name, userResult.Data.EmailAddress),
new Claim("FullName", userResult.Data.FirstName + " " + userResult.Data.LastName),
new Claim(ClaimTypes.Role, "Administrator")
};
OperationResult<string> tokenResult = JwtHandler.GenerateToken(claims);
return Json(tokenResult);
}
所以我想知道我的方法是 jwt 生成器的最佳实践还是最适合它的方法? 还有一件事,我看到有些人使用 httpcontext 作为 jwt 令牌,所以我想知道我什么时候应该使用 httpcontext 作为 jwt,为什么人们使用它?