Introduction
In the previous lesson, we configured JWT Bearer Authentication for a REST API. This lesson focuses on the central part of that design: generating and validating access tokens.
An access token is a portable security credential that an authenticated client presents when calling an API. It can contain the user identifier, roles, permissions, and information describing which service issued the token and which API should accept it. The API must not simply decode the token and trust its contents. It must validate the signature, issuer, audience, and lifetime before creating the authenticated user context.
The examples assume an ASP.NET Core Web API using ASP.NET Core Identity and MSSQL. For teaching purposes, the API will issue tokens itself. In a production architecture, token issuance is commonly delegated to a dedicated and trusted identity provider.
Designing the Access Token Payload
A JWT contains three sections: a header, a payload, and a signature. The header contains metadata such as the signing algorithm. The payload contains claims. The signature allows the recipient to verify that the token was issued by a trusted party and has not been modified.
A JWT payload is encoded, not automatically encrypted. Therefore, never place passwords, signing keys, credit card numbers, or other sensitive secrets inside an access token.
Common access-token claims include:
sub: The stable identifier of the user or subject.email: An identifier such as the user's email address.role: A role assigned to the user. A user may have multiple role claims.permissionorscope: Fine-grained permissions for API operations.iss: The issuer that created the token.aud: The API or resource server intended to receive the token.iat: The time at which the token was issued.jti: A unique token identifier.exp: The token expiration time.
Claim names should be standardized across the application. Mixing role, roles, and framework-specific role claim types without a clear mapping can cause authorization rules to fail unexpectedly.
Configuring JWT Settings
Store the issuer, audience, signing key, and token lifetime in configuration. The signing key in the following example is for development only. Production secrets should be supplied through User Secrets, environment variables, a managed secret store, or an equivalent secure mechanism.
{
"Jwt": {
"Issuer": "https://localhost:7001",
"Audience": "orders-api",
"Key": "development-only-very-long-signing-key-2026",
"AccessTokenMinutes": 15
}
}A symmetric HMAC key must be long, random, and difficult to guess. The application should also have an operational process for protecting, rotating, and replacing signing keys.
Configure JWT validation in Program.cs:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
var jwtSection = builder.Configuration.GetSection("Jwt");
var signingKey = jwtSection["Key"]
?? throw new InvalidOperationException("Jwt:Key is missing.");
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.MapInboundClaims = false;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(signingKey)),
ValidateIssuer = true,
ValidIssuer = jwtSection["Issuer"],
ValidateAudience = true,
ValidAudience = jwtSection["Audience"],
ValidateLifetime = true,
ClockSkew = TimeSpan.FromSeconds(30),
NameClaimType = "sub",
RoleClaimType = "role"
};
});
builder.Services.AddAuthorization();
builder.Services.AddControllers();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();UseAuthentication reads the request credentials and builds the authenticated principal. UseAuthorization evaluates whether that principal satisfies the endpoint's access requirements. The middleware order matters: authorization should run after authentication.
Reading Identity Data
When creating a token, do not copy the entire Identity user record into the payload. Instead, load the verified user through UserManager<ApplicationUser>, retrieve the user's roles, and select only the claims required by the API.
The following service adds Identity roles and permission claims to the token:
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Identity;
using Microsoft.IdentityModel.Tokens;
public sealed class AccessTokenService
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly IConfiguration _configuration;
public AccessTokenService(
UserManager<ApplicationUser> userManager,
IConfiguration configuration)
{
_userManager = userManager;
_configuration = configuration;
}
public async Task<string> CreateAsync(ApplicationUser user)
{
var jwt = _configuration.GetSection("Jwt");
var key = jwt["Key"]
?? throw new InvalidOperationException("Signing key is missing.");
var claims = new List<Claim>
{
new(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
new(JwtRegisteredClaimNames.Email, user.Email ?? string.Empty),
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new(JwtRegisteredClaimNames.Iat,
DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(),
ClaimValueTypes.Integer64)
};
var roles = await _userManager.GetRolesAsync(user);
claims.AddRange(roles.Select(role => new Claim("role", role)));
var identityClaims = await _userManager.GetClaimsAsync(user);
claims.AddRange(identityClaims
.Where(c => c.Type == "permission")
.Select(c => new Claim("permission", c.Value)));
var credentials = new SigningCredentials(
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)),
SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: jwt["Issuer"],
audience: jwt["Audience"],
claims: claims,
notBefore: DateTime.UtcNow,
expires: DateTime.UtcNow.AddMinutes(
int.Parse(jwt["AccessTokenMinutes"] ?? "15")),
signingCredentials: credentials);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}Register the service with dependency injection:
builder.Services.AddScoped<AccessTokenService>();A permission can be assigned to a user through the Identity claims API:
await _userManager.AddClaimAsync(
user,
new Claim("permission", "orders.read"));This design allows roles to represent broad groups, while permission or scope claims express more precise access rules.
Issuing a Token from a Login Endpoint
The login endpoint should locate the user and verify the password through Identity. A token should be issued only after the password check succeeds.
[ApiController]
[Route("api/auth")]
public class AuthController : ControllerBase
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly AccessTokenService _tokens;
public AuthController(
UserManager<ApplicationUser> userManager,
AccessTokenService tokens)
{
_userManager = userManager;
_tokens = tokens;
}
[HttpPost("login")]
public async Task<IActionResult> Login(LoginRequest request)
{
var user = await _userManager.FindByEmailAsync(request.Email);
if (user is null ||
!await _userManager.CheckPasswordAsync(user, request.Password))
{
return Unauthorized(new { message = "Invalid email or password." });
}
var accessToken = await _tokens.CreateAsync(user);
return Ok(new
{
accessToken,
tokenType = "Bearer",
expiresIn = 900
});
}
}
public sealed record LoginRequest(string Email, string Password);Returning the same failure message for an unknown email and an incorrect password helps reduce account-enumeration risk. The login endpoint should also be protected with rate limiting and, where appropriate, Identity lockout policies.
Protecting API Endpoints
Use the Authorize attribute for authenticated access, role requirements for broad access groups, and policies for permission-based rules:
[ApiController]
[Route("api/orders")]
public class OrdersController : ControllerBase
{
[HttpGet]
[Authorize]
public IActionResult GetOrders()
{
var userId = User.FindFirstValue("sub");
return Ok(new { userId, items = Array.Empty<object>() });
}
[HttpDelete("{id:int}")]
[Authorize(Roles = "Admin")]
public IActionResult DeleteOrder(int id)
{
return NoContent();
}
[HttpPost]
[Authorize(Policy = "OrdersWrite")]
public IActionResult CreateOrder()
{
return Ok(new { message = "Order created." });
}
}Register the permission policy as follows:
builder.Services.AddAuthorizationBuilder()
.AddPolicy("OrdersWrite", policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireClaim("permission", "orders.write");
});A missing or invalid credential normally produces 401 Unauthorized. A valid token whose principal lacks the required role or permission produces 403 Forbidden. Clients should distinguish these responses and avoid treating them as the same condition.
Testing with Swagger/OpenAPI
Swagger can be configured to send a Bearer token in the Authorization header. With Swashbuckle, register the security definition and requirement like this:
using Microsoft.OpenApi.Models;
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Name = "Authorization",
Type = SecuritySchemeType.Http,
Scheme = "bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Description = "Enter a token using the Bearer {token} format."
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
Array.Empty<string>()
}
});
});After enabling Swagger middleware in development, select Authorize and enter the token with its Bearer prefix. A protected request should contain a header similar to:
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...Only development tokens should be inspected in online JWT tools. The fact that a payload can be decoded does not mean that it is confidential or trustworthy.
Common Mistakes
- Disabling issuer or audience validation: A token created for another service may be accepted unintentionally.
- Skipping signature validation: An attacker could alter claims such as the role or user ID.
- Putting sensitive data in the payload: JWT encoding does not provide confidentiality.
- Using long-lived access tokens: Short-lived access tokens reduce the impact of token theft. Refresh tokens should be designed separately.
- Using inconsistent claim types: When
roleand framework-specific role claim types are mixed, verify theRoleClaimTypeconfiguration. - Using local time: Use UTC for
iat,nbf, andexpvalues. - Committing the signing key: If the key leaks, an attacker may create valid tokens. Replace a compromised key immediately.
- Confusing 401 and 403: 401 means authentication is missing or invalid; 403 means the authenticated principal is not allowed.
Practice Exercise
- Add the
Microsoft.AspNetCore.Authentication.JwtBearerpackage to an API project. - Configure the
Jwtsection and authentication middleware. - Create a token service that includes the Identity user ID, email, one role, and at least one permission claim.
- Build endpoints protected by
[Authorize],[Authorize(Roles = "Admin")], and a permission policy. - Add a Bearer security definition to Swagger.
- Test an invalid issuer, an expired token, a missing role, and a missing permission separately.
Answer these questions after completing the exercise: Why should the audience identify the API? What problem can a small ClockSkew value address? Why does changing a user's role in the database not immediately change an already-issued token?
Conclusion
An access token is not merely a string returned by a login endpoint. It is a security artifact that must be designed carefully, signed by a trusted issuer, and fully validated by the receiving API. We retrieved roles and permissions from ASP.NET Core Identity, converted them into claims, created a signed token, and configured validation for issuer, audience, signature, and lifetime.
In the next lesson, we will address session continuity and short token lifetimes by implementing a refresh-token mechanism. The key principle from this lesson is simple: generating a token securely is only half of the solution; validating it correctly is equally essential.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/security/authentication/configure-jwt-bearer-authentication?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis/security?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/security/authorization/limitingidentitybyscheme?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.jwtbearer.jwtbeareroptions?view=aspnetcore-10.0