首页 > 解决方案 > 是否有现成可用的“GenerateJwt”方法?

问题描述

我将Microsoft.AspNetCore.Authentication.JwtBearerSystem.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)

标签: c#.net-coreasp.net-core-webapiadal

解决方案


Microsoft 库本身不支持发布令牌,因此在 Microsoft 库中没有您正在寻找的命令。然而,微软确实使用他们的服务 azure ad 发布令牌作为身份服务器,这可能是他们最简单的方法。如果您只是这样做,那么您的做法基本上没问题。而不是完整的身份验证框架,这是一个与您做非常相似的事情的人的示例:https ://jasonwatmore.com/post/2019/10/11/aspnet-core-3-jwt-authentication-tutorial-with-example- api

如果您希望实现自己的完整身份验证服务,可以颁发令牌。有一些相对常见的 3rd 方库可以帮助您不必重新发明轮子,其中之一是 identityserver4: https ://identityserver4.readthedocs.io/en/latest/index.html 它是一个完整的身份提供者解决方案。另一个是 openiddict https://devblogs.microsoft.com/aspnet/bearer-token-authentication-in-asp-net-core/


推荐阅读