Hi @coder rock,
If you want to use JWT auth inside the web api, you need firstly install the jwt package:
Microsoft.AspNetCore.Authentication.JwtBearer
Then you could add the jwt auth related codes inside the program.cs and add app.UseAuthentication(); middleware:
Like below, if you want you could modify the Issuer, audience, signingkey by yourself:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "your-issuer",
ValidAudience = "your-audience",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("xxxxxxxassaaaaaaasdddxxxxxxxxxxxxxxxx"))
};
});
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Then inside the user controller we could generate the token and use that token to access the protected web api method.
Please notice: My sample doesn't contain the username and password verify, you could modify the codes to verify username and password based on the request body and then set the user role based on the username inside the GenerateJwtToken method.
[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
[HttpPost("authenticate")]
public async Task<IActionResult> Authenticate()
{
//Here you could pass user to generatejwttoeknmethod to generate the token based on the user
var token = GenerateJwtToken( );
if (token == null)
return BadRequest(new { message = "Username or password is incorrect" });
return Ok(token);
}
private string GenerateJwtToken( )
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes("xxxxxxxassaaaaaaasdddxxxxxxxxxxxxxxxx");
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[] { new Claim("id", "testuser"), new Claim(ClaimTypes.Role, "Admin") }),
Issuer = "your-issuer",
Audience = "your-audience",
Expires = DateTime.UtcNow.AddDays(7),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
public async Task<IActionResult> Register( )
{
return Ok();
}
[HttpGet]
[Authorize(Roles = "Admin")]
public async Task<IActionResult> GetAll()
{
return Ok("success");
}
}
Test Result:
Authencation:
Access admin role api method:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.