Module 3: Identity, Tokens, and Authorization
1:00 – 2:15 PM · Concepts 25 min · Lab 45 min
Learning objectives
By the end of this module you can add ASP.NET Core Identity with token endpoints, protect endpoints with JWT bearer authentication, express permissions as policies rather than role checks scattered through code, and harden the API against the most common attacks.
Authentication and authorization are different questions
Authentication answers "who is this?" and produces a ClaimsPrincipal. Authorization answers "may they do this?" and produces allow or deny. They are separate middleware, and the order is not negotiable:
Anything that needs to know who the caller is must run after UseAuthentication. Keep that in mind when you get to rate limiting below.
flowchart LR
Req[Request + Bearer token] --> A[UseAuthentication\nvalidate JWT → ClaimsPrincipal]
A --> Z[UseAuthorization\nevaluate policy]
Z -->|allowed| H[Handler]
Z -->|no principal| U[401 Unauthorized]
Z -->|principal, policy fails| F[403 Forbidden]Two ways to get a token
MapIdentityApi<TUser>() gives you register, login, refresh, confirm-email, password-reset, and account-management endpoints for free. It is a superb starting point for account management.
Its /login endpoint, however, signs in through Identity's own bearer-token scheme (Identity.Bearer), and the token it returns is an opaque, data-protected string, not a JWT. The all-in-one AddIdentityApiEndpoints<TUser>() registers that scheme for you. Roastery uses the leaner AddIdentityCore<TUser>().AddApiEndpoints(), which registers what the endpoints need (sign-in manager, token providers, a no-op email sender) but not the scheme. Without it, /login fails with 500 and "No sign-in authentication handlers are registered… Identity.Bearer". So we register it ourselves with one call, .AddBearerToken(IdentityConstants.BearerScheme), next to JWT bearer (shown below). The two setup methods look interchangeable and are not.
JWT bearer stays the default scheme, so the endpoints only accept our JWTs. An Identity token from /login gets 401 from /api/orders: it carries none of our claims, and nothing is configured to read it.
Issuing your own JWT gives you control over the claims. Roastery needs a customer_id claim and a role claim so that authorization can work without a database round-trip on every request.
So we use both: Identity's endpoints for account management (/register and friends), and a small POST /api/auth/token that checks the password with UserManager.CheckPasswordAsync and issues a JWT. That is the only place Roastery tokens come from.
public record TokenRequest(string Email, string Password);
public record TokenResponse(string AccessToken, string TokenType = "Bearer");
static async Task<Results<Ok<TokenResponse>, UnauthorizedHttpResult>> IssueToken(
TokenRequest request, UserManager<RoasteryUser> users, IOptions<JwtOptions> jwtOptions)
{
var user = await users.FindByEmailAsync(request.Email);
if (user is null || !await users.CheckPasswordAsync(user, request.Password))
return TypedResults.Unauthorized();
var jwt = jwtOptions.Value;
var roles = await users.GetRolesAsync(user);
var claims = new List<Claim>
{
new(JwtRegisteredClaimNames.Sub, user.Id),
new(JwtRegisteredClaimNames.Email, user.Email!),
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
};
// Staff have no customer row, so they get no customer_id claim.
if (user.CustomerId is int cid) claims.Add(new Claim("customer_id", cid.ToString()));
claims.AddRange(roles.Select(r => new Claim(ClaimTypes.Role, r)));
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwt.SigningKey));
var token = new JwtSecurityToken(
issuer: jwt.Issuer, audience: jwt.Audience, claims: claims,
expires: DateTime.UtcNow.AddMinutes(jwt.LifetimeMinutes),
signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));
return TypedResults.Ok(new TokenResponse(new JwtSecurityTokenHandler().WriteToken(token)));
}
The JSON property is accessToken (camelCase of AccessToken). The .http file captures it by that name, so do not rename it.
warning No lockout here
CheckPasswordAsync only compares the password; it never counts failures or locks the account. The rate limiter below is our brute-force defense. In production prefer SignInManager.CheckPasswordSignInAsync(user, password, lockoutOnFailure: true), which honors Identity's lockout settings. It needs AddSignInManager() on the Identity builder.
Validating the token
builder.Services.Configure<JwtOptions>(builder.Configuration.GetSection(JwtOptions.SectionName));
var jwt = builder.Configuration.GetSection(JwtOptions.SectionName).Get<JwtOptions>() ?? new JwtOptions();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateIssuerSigningKey = true,
ValidateLifetime = true,
ValidIssuer = jwt.Issuer,
ValidAudience = jwt.Audience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwt.SigningKey)),
ClockSkew = TimeSpan.FromSeconds(30),
};
})
// Lets MapIdentityApi's /login and /refresh work. JWT stays the default scheme.
.AddBearerToken(IdentityConstants.BearerScheme);
The signing key never lives in appsettings.json. In development, use user secrets (run this in src/Roastery.Api, the project folder):
dotnet user-secrets set "Jwt:SigningKey" "a-development-key-that-is-at-least-32-bytes-long!"
User secrets override appsettings.Development.json. The checkpoint also carries a clearly labelled dev-only key in appsettings.Development.json so it runs straight after git checkout; that file is never deployed.
In production it comes from an environment variable or a key vault, which is exactly how Module 5 passes it into the container.
warning
HS256 requires a key of at least 256 bits (32 bytes). A shorter key throws at token creation with a message that is easy to misread as a configuration typo.
Authorization as policy
Scattering if (user.IsInRole("Staff")) through handlers is how permission bugs are born. Declare the rules once as named policies and apply them to groups. Here the public reads and the staff-only writes share one prefix, so the writes live in a sub-group:
Applying the policy to the group means a new endpoint added tomorrow is protected by default. Applying it endpoint by endpoint means a new endpoint is open by default. Choose the default that fails safe.
Resource-based authorization
"A customer may see only their own orders" is not a role check; it depends on the order. That is an IAuthorizationHandler that receives the resource:
Notice the last line returns NotFound, not Forbid, when a customer asks for someone else's order. A 403 confirms the order exists; a 404 reveals nothing. The lab asks you to decide which is right for each endpoint.
Never trust the body for identity
In Lab 2, CreateOrder hard-coded CustomerId = 1. The fix is not to accept it from the request; it is to read it from the token:
// No customer record, no orders: fail closed with 403 rather than throwing.
if (!int.TryParse(user.FindFirstValue("customer_id"), out var customerId))
return TypedResults.Forbid();
Forbid() adds ForbidHttpResult to the handler's return type: Results<CreatedAtRoute<OrderDto>, ValidationProblem, ForbidHttpResult>.
A request body that carries customerId is an invitation to place orders as someone else. This is OWASP API1, Broken Object Level Authorization, and it is the most common API vulnerability in the wild.
The other half of API1 is deciding what happens when the claim is missing. Anyone can call /api/auth/register, and a self-registered user has no role and no customer_id. Code that says "filter to the caller's orders if they have a customer_id" quietly shows that user everything. Authorization code should fail closed: no claim, no data. In Roastery, a non-staff caller without a customer_id gets an empty order list and a 403 from POST /api/orders.
Hardening quick hits
Each of these is a few lines. The lab adds all of them.
builder.Services.AddRateLimiter(options =>
{
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.AddFixedWindowLimiter("auth", o =>
{
o.Window = TimeSpan.FromMinutes(1);
o.PermitLimit = 5;
o.QueueLimit = 0;
});
// UseRateLimiter runs before UseAuthentication, so there is no user yet: partition by client IP.
options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(context =>
RateLimitPartition.GetSlidingWindowLimiter(
context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
_ => new SlidingWindowRateLimiterOptions
{
Window = TimeSpan.FromSeconds(10), PermitLimit = 100, SegmentsPerWindow = 5, QueueLimit = 0
}));
});
// …
app.UseRateLimiter();
var auth = app.MapGroup("/api/auth").WithTags("Auth").RequireRateLimiting("auth");
Two things about this configuration are worth saying out loud:
- The
"auth"limiter is one bucket.AddFixedWindowLimiteris not partitioned, so every request to every/api/auth/*endpoint, from every caller, shares the same 5 permits a minute. That is fine for a workshop and too blunt for production, where you would partition by IP (and by the email being attempted) withAddPolicyandRateLimitPartition.GetFixedWindowLimiter. - The global limiter partitions by IP, not by user.
UseRateLimiterruns beforeUseAuthentication, socontext.Useris still anonymous when the limiter runs; reading the user name there would always fall through to the IP anyway. To partition authenticated callers by user, moveUseRateLimiter()afterUseAuthentication()and key oncontext.User.Identity?.Name.
warning Removing the Server header
context.Response.Headers.Remove("Server") in middleware does nothing useful: Kestrel adds Server: Kestrel when the response starts, after your middleware has run. The right switch is on Kestrel itself, and it is what the checkpoint uses: builder.WebHost.ConfigureKestrel(o => o.AddServerHeader = false);.