English
Authentication endpoints
Step 1. Where the browser keeps the refresh token
Why. Topic 8 created two tokens. The access token lives 15 minutes; the Angular app keeps it in memory and sends it in the Authorization header. The refresh token lives 30 days and is far more valuable. If page scripts could read it, a single cross-site scripting bug would let an attacker steal 30-day sessions.
So the refresh token never reaches JavaScript at all. The server puts it into a cookie with four protective attributes:
HttpOnly— page scripts cannot read the cookie;Secure— it is sent only over HTTPS (browsers make an exception forlocalhost);SameSite=Strict— the browser does not send it with requests started by other sites, which blocks cross-site request forgery;Path=/api/auth— it is sent only to the auth endpoints, not with every API request.
Do.
cs
using Chatex.Core.Auth;
namespace Chatex.Api.Infrastructure;
/// <summary>
/// The refresh token lives in an HttpOnly cookie that only the auth endpoints receive, so page scripts never see it.
/// SameSite=Strict keeps other sites from sending it along.
/// </summary>
internal static class RefreshTokenCookie
{
public const string Name = "chatex_refresh";
public const string Path = "/api/auth";
public static void Set(HttpResponse response, AuthResult auth) =>
response.Cookies.Append(Name, auth.RefreshToken, Options(auth.RefreshTokenExpiresAt));
public static string? Read(HttpRequest request) =>
request.Cookies.TryGetValue(Name, out var token) && !string.IsNullOrEmpty(token) ? token : null;
public static void Clear(HttpResponse response) => response.Cookies.Delete(Name, Options(expires: null));
private static CookieOptions Options(DateTimeOffset? expires) => new()
{
HttpOnly = true,
Secure = true,
SameSite = SameSiteMode.Strict,
Path = Path,
Expires = expires,
IsEssential = true,
};
}Clear deletes the cookie by sending it again with an expiry date in the past; the attributes must match the original, or the browser keeps the old cookie.
Step 2. The endpoints
Why. Five endpoints wrap the auth service. Four of them are anonymous — you cannot be signed in while signing in — and the fifth, "sign out everywhere", requires a token. The JSON response of a successful sign-in carries the access token and the profile; the refresh token goes into the cookie.
Do. Create the folder Endpoints:
cs
using System.Security.Claims;
using Chatex.Api.Contracts;
using Chatex.Api.Infrastructure;
using Chatex.Core.Auth;
using Chatex.Core.Common;
using Microsoft.AspNetCore.Http.HttpResults;
namespace Chatex.Api.Endpoints;
internal static class AuthEndpoints
{
public static void MapAuthEndpoints(this IEndpointRouteBuilder routes)
{
var group = routes.MapGroup("/auth").WithTags("Auth");
group.MapPost("/register", RegisterAsync).AllowAnonymous().WithName("Register")
.WithSummary("Creates an account and signs it in.");
group.MapPost("/login", LoginAsync).AllowAnonymous().WithName("Login")
.WithSummary("Signs in with a user name or email.");
group.MapPost("/refresh", RefreshAsync).AllowAnonymous().WithName("Refresh")
.WithSummary("Swaps the refresh token cookie for a new access token and cookie.");
group.MapPost("/logout", LogoutAsync).AllowAnonymous().WithName("Logout")
.WithSummary("Ends the session of the refresh token cookie.");
group.MapPost("/logout-all", LogoutAllAsync).WithName("LogoutAll")
.WithSummary("Ends every session of the signed-in user.");
}
private static async Task<Results<Ok<AuthResponse>, ProblemHttpResult>> RegisterAsync(
RegisterCommand command, IAuthService auth, HttpContext context, CancellationToken cancellationToken) =>
SignIn(await auth.RegisterAsync(command, context.GetClientInfo(), cancellationToken), context.Response);
private static async Task<Results<Ok<AuthResponse>, ProblemHttpResult>> LoginAsync(
LoginCommand command, IAuthService auth, HttpContext context, CancellationToken cancellationToken) =>
SignIn(await auth.LoginAsync(command, context.GetClientInfo(), cancellationToken), context.Response);
private static async Task<Results<Ok<AuthResponse>, ProblemHttpResult>> RefreshAsync(
IAuthService auth, HttpContext context, CancellationToken cancellationToken)
{
var token = RefreshTokenCookie.Read(context.Request);
var result = token is null
? AuthErrors.InvalidRefreshToken
: await auth.RefreshAsync(new RefreshCommand(token), context.GetClientInfo(), cancellationToken);
if (!result.IsSuccess)
{
RefreshTokenCookie.Clear(context.Response);
}
return SignIn(result, context.Response);
}
private static async Task<Results<NoContent, ProblemHttpResult>> LogoutAsync(
IAuthService auth, HttpContext context, CancellationToken cancellationToken)
{
var token = RefreshTokenCookie.Read(context.Request);
var result = token is null ? Result.Success : await auth.LogoutAsync(new RefreshCommand(token), cancellationToken);
RefreshTokenCookie.Clear(context.Response);
return result.ToNoContent();
}
private static async Task<Results<NoContent, ProblemHttpResult>> LogoutAllAsync(
ClaimsPrincipal user, IAuthService auth, HttpResponse response, CancellationToken cancellationToken)
{
var result = await auth.LogoutAllAsync(user.GetUserId(), cancellationToken);
if (result.IsSuccess)
{
RefreshTokenCookie.Clear(response);
}
return result.ToNoContent();
}
private static Results<Ok<AuthResponse>, ProblemHttpResult> SignIn(Result<AuthResult> result, HttpResponse response)
{
if (!result.IsSuccess)
{
return result.Error.ToProblem();
}
RefreshTokenCookie.Set(response, result.Value);
return TypedResults.Ok(AuthResponse.From(result.Value));
}
}MapAuthEndpointsis an extension method onIEndpointRouteBuilder.Program.cswill call it on a group that already has the prefix/apiand requires authorization for everything;AllowAnonymous()lifts that requirement for four endpoints.WithTags,WithName,WithSummaryare metadata for OpenAPI: the endpoints appear grouped under "Auth", each with an operation id and a description.- Parameters:
RegisterCommand commandis read from the JSON body,IAuthService authfrom dependency injection,HttpContext contextgives access to the request and the response. SignInis shared by register, login and refresh: on success it sets the cookie and returns200withAuthResponse; on failure it returns the problem.RefreshAsyncreads the token from the cookie, not from the body. A failed refresh also clears the cookie, so a browser with a dead token stops sending it.LogoutAsyncalways clears the cookie, even without a valid token.
In topic 13 this file gets one more call: rate limiting for the whole group.
Check
dotnet build succeeds.