I have created an API project using .NetCore 6. I have followed the tutorials and I think I have not missed anything. I run the program and it works fine not until I have implemented to only Authorize user has access to it.
So I have implement JWT Authentication. I have verified the token in https://jwt.io/ and I got a signature Verified. But when I tried to call the method that has [Authorize] keywork via POSTMAN, I am getting a 401 Unauthorized as a response. Can someone help me with this? Here are the relevant codes in the implementation.
*********** API ENDPOINT ***********
[Authorize]
[HttpGet]
public async Task<ActionResult<IEnumerable<User>>> GetUsers()
{
if (_context.Users == null)
{
return NotFound();
}
return await _context.Users.ToListAsync();
}
*********** 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"]))
};
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseCors();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
*********** 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("lectureTest12345"));
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);
}