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
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 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.