我将Microsoft.AspNetCore.Authentication.JwtBearer和System.IdentityModel.Tokens.Jwt用于我的.NET Core项目。在我的启动文件中,运行[Authorize]
注释的配置设置。当我使用自己的方法(示例)生成新令牌时,这对我来说效果很好
public object GenerateToken(Dictionary<string, object> payload)
{
DateTime tokenExpiresAt = DateTime.Now.AddMilliseconds(1); // From config
byte[] symmetricKey = Convert.FromBase64String("secret"); // from config
SymmetricSecurityKey symmetricSecurityKey = new SymmetricSecurityKey(symmetricKey);
SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
{
Claims = payload,
Expires = tokenExpiresAt,
SigningCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256Signature)
};
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.CreateToken(tokenDescriptor);
string token = tokenHandler.WriteToken(securityToken);
return new { token, tokenExpiresAt };
}
令牌的验证不需要执行,因为它是通过[Authorize]
注释完成的。我想知道是否有一种方法可以用来生成令牌,而不必自己编写代码?我将生成的令牌存储到数据库中,并且还需要返回到期时间。
所以是的,上面的解决方案对我来说很好,但也许是多余的:)
是否有采用令牌机密,有效负载和令牌到期时间的方法?例如TokenGenerator.Sign("secret", payload, tokenExpiresAt)
?
Microsoft库不支持本地发行令牌,因此Microsoft库中没有您想要的命令。但是,Microsoft确实会使用其服务蓝色广告将令牌作为身份服务器发行,这可能是它们最简单的方法。如果您只是这样做,那么您的工作方式基本上是可以的。而不是完整的身份验证框架,这是一个与您做非常相似的事情的示例:https://jasonwatmore.com/post/2019/10/11/aspnet-core-3-jwt-authentication-tutorial-with-example- api
如果您希望实施自己的完整身份验证服务,可以发行令牌。有一些相对通用的第三方库可以帮助您不必重新发明轮子,其中之一就是Identityserver4:https : //identityserver4.readthedocs.io/en/latest/index.html这是一个完整的身份提供程序解决方案。另一个是openiddict https://devblogs.microsoft.com/aspnet/bearer-token-authentication-in-asp-net-core/
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句