I have tried to implement JWT authentication to an API. I am following the tutorials. So far I can get the token, but when I checked the token in https://jwt.io/, I am getting an invalid signature.
Here are the codes that I used.
Program.cs
:
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidateAudience = true,
ValidAudience = builder.Configuration["Jwt:Audience"],
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(
builder.Configuration["Jwt:Key"]))
};
});
appsettings.json
:
"Jwt": {
"Key": "lectureTest123456",
"Issuer": "https://localhost:44387",
"Audience": "https://localhost:44387",
"Subject": "JWTServiceAccessToken"
},
And in the class that generates the token
private string GetToken()
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, _configuration["Jwt:Subject"]),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Iat, "1516239022"),
new Claim("userId" , "1"),
new Claim("name", "Jason"),
new Claim("userName", "Jason"),
new Claim("email", "jason@gmail.com")
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("lectureTest123456"));
var singIn = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
_configuration["Jwt: Issuer"],
_configuration["Jwt:Audience"],
claims,
expires: DateTime.UtcNow.AddHours(1),
signingCredentials: singIn
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
What seems to be the issue?
I am expecting that the JWT token is a valid one.