Error trying to generate token using .NET JWT library

前端 未结 1 1149
别跟我提以往
别跟我提以往 2021-02-05 16:24

I\'m trying to use package System.IdentityModel.Tokens.Jwt to generate a token. I found some code samples online, was pretty straightforward, but then I\'m running into an error

相关标签:
1条回答
  • 2021-02-05 16:48

    I ran into a similar situation with the OpenID Connect library when I upgraded, which previously was in the Microsoft.IdentityModel.Protocol.Extensions package (which depended on 4.0.2 of the JWT package) but now is Microsoft.IdentityModel.Protocols.OpenIdConnect which depends on 2.0.0 of Microsoft.IdentityModel.Protocols (which depends on 5.0.0 of the JWT package).

    Remove any of your Microsoft.IdentityModel* and System.IdentityModel* packages, and install only the latest (5.0.0) System.IdentityModel.Tokens.Jwt package which depends on Microsoft.IdentityModel.Tokens.

    You'll want using statements for these namespaces:

    • Microsoft.IdentityModel.Tokens (but not System.IdentityModel.Tokens)
    • System.IdentityModel.Tokens.Jwt
    • System.Security.Claims

    Microsoft has simplified some of the parameters to be more like what you would expect from other platforms' JWT libraries, so the SecurityTokenDescriptor properties are a little different:

    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(new[]
        {
            new Claim( ClaimTypes.UserData,
            "IsValid", ClaimValueTypes.String, "(local)" )
        }),
        Issuer = "self",
        Audience = "https://www.mywebsite.com",
        Expires = now.AddMinutes(60),
        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(securityKey), SecurityAlgorithms.HmacSha256),
    };
    

    Note that SecurityAlgorithms.HmacSha256 is a string constant for "HS256", just like you'd use in most other libraries. Using the above code plus the example in your question, you should be able to generate a valid JWT.

    0 讨论(0)
提交回复
热议问题