Introduction
Previous lessons covered ASP.NET Core Identity, user management, roles, claims and policy-based authorization. This lesson connects that identity infrastructure to the token-based access model commonly used by REST APIs.
In an MVC application, a browser may carry an authentication cookie. In a REST API scenario, the client usually sends an Authorization: Bearer <token> header with each request. The API parses the token and checks whether its signature, lifetime, issuer and audience match the expected values. When validation succeeds, the token claims are made available through HttpContext.User.
The goal is not merely to create a working login endpoint. A maintainable implementation must also separate token creation from token validation, protect signing secrets and configure the middleware pipeline correctly.
How JWT Bearer Authentication Works
A JWT normally contains three sections: header, payload and signature. The sections are separated by periods. The header describes the algorithm, while the payload contains claims such as issuer, audience, subject and expiration. The signature proves that the token was signed with a trusted key.
The JWT payload is not encrypted. It is Base64Url-encoded and can be decoded by anyone who possesses the token. The signature protects integrity, not confidentiality. Never place a password, credit-card number or other sensitive information in a JWT payload.
With the bearer model, any party holding the token can attempt to use the permissions represented by that token. For this reason, access tokens should have a short lifetime, contain only necessary claims and be transmitted over HTTPS. Authentication alone does not grant access to every endpoint; authorization rules must still be applied.
Preparing Project Settings
Assume that the project is an ASP.NET Core Web API application already using ASP.NET Core Identity. Instead of reading individual JWT settings inside a controller, group them in a strongly typed options class. This improves separation of concerns and makes validation easier.
public sealed class JwtOptions
{
public const string SectionName = "Jwt";
public string Issuer { get; init; } = string.Empty;
public string Audience { get; init; } = string.Empty;
public string SigningKey { get; init; } = string.Empty;
public int AccessTokenMinutes { get; init; } = 15;
}Non-sensitive settings such as issuer and audience may be stored in appsettings.json for development. The signing key must not be written to source code or committed to a Git repository.
{
"Jwt": {
"Issuer": "SecureApi",
"Audience": "SecureApi.Client",
"AccessTokenMinutes": 15
}
}User Secrets can be used on a development machine:
dotnet user-secrets init
dotnet user-secrets set "Jwt:SigningKey" "development-only-long-random-secret-key"Production environments should use a controlled secret-management solution, environment variables or a service such as Azure Key Vault. The length and randomness of the signing key must be appropriate for the selected signing algorithm. This lesson uses HMAC-SHA256, commonly identified as HS256.
Creating the Token Service
Keep token creation outside the controller by introducing a dedicated service. The service receives a user that has already been validated by Identity and creates a short-lived access token containing the required claims.
public interface IAccessTokenService
{
string CreateAccessToken(ApplicationUser user);
}using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.Text;
public sealed class AccessTokenService : IAccessTokenService
{
private readonly JwtOptions _options;
public AccessTokenService(IOptions<JwtOptions> options)
{
_options = options.Value;
}
public string CreateAccessToken(ApplicationUser user)
{
if (string.IsNullOrWhiteSpace(_options.SigningKey))
throw new InvalidOperationException("JWT signing key is not configured.");
var claims = new List<Claim>
{
new(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
new(JwtRegisteredClaimNames.UniqueName, user.UserName ?? string.Empty),
new(ClaimTypes.NameIdentifier, user.Id.ToString())
};
var key = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(_options.SigningKey));
var credentials = new SigningCredentials(
key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: _options.Issuer,
audience: _options.Audience,
claims: claims,
notBefore: DateTime.UtcNow,
expires: DateTime.UtcNow.AddMinutes(_options.AccessTokenMinutes),
signingCredentials: credentials);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}The sub claim represents the user's stable identifier. A persistent user ID is preferable to a username, which may be changed. If roles or permission claims are needed, they can also be added during token creation, but claims should remain minimal so that tokens do not become unnecessarily large.
Configuring the JWT Bearer Middleware
Now configure validation in Program.cs. Token creation and token validation must use the same issuer, audience and signing key. If even one of these values differs, the token should be rejected.
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Security.Claims;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOptions<JwtOptions>()
.Bind(builder.Configuration.GetSection(JwtOptions.SectionName))
.Validate(options => !string.IsNullOrWhiteSpace(options.Issuer),
"JWT issuer is required.")
.Validate(options => !string.IsNullOrWhiteSpace(options.Audience),
"JWT audience is required.")
.Validate(options => !string.IsNullOrWhiteSpace(options.SigningKey),
"JWT signing key is required.")
.ValidateOnStart();
var jwt = builder.Configuration
.GetSection(JwtOptions.SectionName)
.Get<JwtOptions>() ?? throw new InvalidOperationException("JWT settings are missing.");
var signingKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(jwt.SigningKey));
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.MapInboundClaims = false;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ValidateIssuer = true,
ValidIssuer = jwt.Issuer,
ValidateAudience = true,
ValidAudience = jwt.Audience,
ValidateLifetime = true,
ClockSkew = TimeSpan.FromSeconds(30),
NameClaimType = "unique_name",
RoleClaimType = ClaimTypes.Role
};
});
builder.Services.AddAuthorization();
builder.Services.AddScoped<IAccessTokenService, AccessTokenService>();
builder.Services.AddControllers();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();UseAuthentication creates the user identity from the bearer token. UseAuthorization evaluates endpoint permissions. Authentication must run before authorization so that authorization can inspect the authenticated principal.
ValidateIssuerSigningKey verifies the token signature with the expected key. ValidateIssuer checks who issued the token, while ValidateAudience confirms which API the token targets. ValidateLifetime prevents expired tokens from being accepted.
Building the Login Endpoint
The login endpoint should not compare passwords manually. It should use Identity's UserManager and its established password validation mechanisms.
public sealed record LoginRequest(string UserName, string Password);
public sealed record LoginResponse(string AccessToken, DateTime ExpiresAtUtc);
[ApiController]
[Route("api/auth")]
public sealed class AuthController : ControllerBase
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly IAccessTokenService _tokenService;
private readonly IOptions<JwtOptions> _jwtOptions;
public AuthController(
UserManager<ApplicationUser> userManager,
IAccessTokenService tokenService,
IOptions<JwtOptions> jwtOptions)
{
_userManager = userManager;
_tokenService = tokenService;
_jwtOptions = jwtOptions;
}
[HttpPost("login")]
public async Task<ActionResult<LoginResponse>> Login(LoginRequest request)
{
var user = await _userManager.FindByNameAsync(request.UserName);
if (user is null || !await _userManager.CheckPasswordAsync(user, request.Password))
return Unauthorized(new { message = "Invalid credentials." });
var token = _tokenService.CreateAccessToken(user);
var expires = DateTime.UtcNow.AddMinutes(_jwtOptions.Value.AccessTokenMinutes);
return Ok(new LoginResponse(token, expires));
}
}Returning one generic message for both an unknown username and an incorrect password makes account enumeration more difficult. Failed login attempts should also be supported by logging, rate limiting and, when appropriate, an account lockout policy.
Protecting an Endpoint and Sending the Token
Adding Authorize to a controller or action requires a valid bearer token.
[ApiController]
[Route("api/profile")]
[Authorize]
public sealed class ProfileController : ControllerBase
{
[HttpGet]
public IActionResult GetProfile()
{
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
return Ok(new { userId });
}
}The client sends the token in a request header:
GET /api/profile HTTP/1.1
Host: localhost:5001
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...A missing or invalid token normally produces 401 Unauthorized. A successfully authenticated user who lacks the required role or policy should receive 403 Forbidden. This distinction is useful when designing client-side error handling.
Common Mistakes
- Putting the signing key in appsettings.json: Use a secret store or secure deployment configuration outside development.
- Disabling issuer and audience validation: These checks reduce the risk of accepting a token intended for another API.
- Creating long-lived access tokens: If a token is exposed, a long lifetime extends the attacker's access. Keep access tokens short-lived.
- Assuming JWT is encrypted: The payload can be read. Do not place sensitive information in it.
- Confusing authentication with authorization: A valid token does not mean that the user may access every resource.
- Using local time: Use
DateTime.UtcNowfor token timestamps and keepClockSkewlimited. - Changing middleware order:
UseAuthenticationmust appear beforeUseAuthorization. - Adding excessive claims: Include only data required by the API's authorization and application logic.
Short Practice Exercise
- Create a
JwtOptionsclass in an ASP.NET Core Web API project. - Put the issuer and audience in configuration and store the signing key with User Secrets.
- Implement
AccessTokenServiceand register it in dependency injection. - Configure JWT Bearer validation with issuer, audience, signing-key and lifetime validation enabled.
- Build a login endpoint using Identity.
- Add a profile endpoint protected by
[Authorize]. - Use Swagger or another HTTP client to compare the results of requests with no token, an invalid token and a valid token.
Conclusion
JWT Bearer Authentication provides REST APIs with a signed proof of identity that the client carries on each request. A secure implementation requires coordinated decisions about token creation, secret management and validation.
In this lesson, we generated an access token from an Identity user, enabled issuer, audience, expiration and signing-key validation, configured the bearer middleware in the correct order and protected an API endpoint. The next step is to introduce refresh tokens, token renewal, revocation and secure token-storage strategies.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/security/authentication/configure-jwt-bearer-authentication?view=aspnetcore-9.0
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-10.0