1.Configure Authentication and Authorization in Program.cs: In .NET 8.0, authentication and authorization are configured directly in the Program.cs file. If you're using JWT tokens for authentication, follow these steps:
var builder = WebApplication.CreateBuilder(args);
// Configure Authentication using JWT Bearer
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "https://your-authority-url"; // The identity provider (e.g., Azure AD, IdentityServer)
options.Audience = "your-api-audience"; // The audience your token is intended for
});
// Configure Authorization
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseRouting();
// Ensure Authentication and Authorization are applied in order
app.UseAuthentication(); // Authenticate the user
app.UseAuthorization(); // Authorize the user based on roles or policies
app.MapControllers();
app.Run();
2.Secure Controllers or Actions Using the [Authorize] Attribute: Use the [Authorize] attribute to restrict access to specific controllers or actions, allowing only authenticated users.
[Authorize] // Ensures only authenticated users can access this controller
[ApiController]
[Route("api/[controller]")]
public class YourController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return Ok("You are authorized!");
}
}
3.Send JWT Token in API Requests: When making requests to the API, ensure the JWT token is included in the HTTP request header as shown below:
Authorization: Bearer <your-jwt-token>
JwtBearerDefaults.AuthenticationScheme handles JWT-based authentication.
Authority is the URL of the identity provider (e.g., Azure AD, IdentityServer).
Audience must match the audience claim (aud) in the JWT token.
Ensure the JWT token is valid and includes the necessary claims (like aud).
Verify that the token has not expired before making the request.
Please feel free to contact us if you have any additional questions.
If you have found the answer provided to be helpful, please click on the "Accept answer/Upvote" button so that it is useful for other members in the Microsoft Q&A community.
Thank you.