English
Tokens
Step 1. Two tokens
Why. After signing in, the browser must prove who it is with every request. Chatex uses two tokens with different jobs (Table 8.1):
Table 8.1. Access token and refresh token
| Access token | Refresh token | |
|---|---|---|
| What it is | a signed JWT with the user id | 32 random bytes |
| Lifetime | 15 minutes | 30 days |
| Sent with | every API request and the SignalR connection | only POST /api/auth/refresh |
| Kept by the browser | in memory of the Angular app | in an HttpOnly cookie (topic 13) |
| Kept by the server | nowhere — the signature proves it | a SHA-256 hash in refresh_tokens |
| Can be revoked | no, it simply expires | yes, at any time |
The split combines the strengths of both. Checking an access token needs no database: the API verifies the signature and the expiry, which is fast for every request and every WebSocket message. But such a token cannot be revoked, so it lives only 15 minutes. The refresh token is checked against the database, so it can be revoked — on sign-out, on a password change, when theft is detected — and it renews the access token every 15 minutes.
A JWT from the inside
A JSON Web Token (RFC 7519) is three Base64Url parts separated by dots: a header ({"alg":"HS256","typ":"JWT"}), a payload with claims ({"sub":"0199…","unique_name":"alice","exp":1763213400,…}) and a signature over the first two parts. Anybody can read the payload — paste a token into jwt.io — but only the holder of the key can produce a valid signature. Chatex signs with HMAC-SHA256: one secret key, known only to the server, both signs and verifies. Never put secrets into claims.
Step 2. Packages
Do. The business layer needs four more packages: the JWT library, FluentValidation's registration helpers and the options extensions that bind and validate settings.
powershell
dotnet add Source/Chatex.Core package Microsoft.IdentityModel.JsonWebTokenspowershell
dotnet add Source/Chatex.Core package FluentValidation.DependencyInjectionExtensionspowershell
dotnet add Source/Chatex.Core package Microsoft.Extensions.Options.ConfigurationExtensionspowershell
dotnet add Source/Chatex.Core package Microsoft.Extensions.Options.DataAnnotationsxml
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\Chatex.Data\Chatex.Data.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="FluentValidation" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" />
<PackageReference Include="Microsoft.Extensions.Options.DataAnnotations" />
<PackageReference Include="Microsoft.IdentityModel.JsonWebTokens" />
</ItemGroup>
</Project>The project file is now final.
Step 3. Token settings
Why. The issuer, the audience, the signing key and the two lifetimes are settings: the development key lives in appsettings.Development.json, the production key in an environment variable on the server. The options pattern binds them to a class, and data annotations on the properties declare what valid settings look like. A key of 10 characters must stop the application at start-up, not make every sign-in fail later.
Do. Create the folder Auth:
cs
using System.ComponentModel.DataAnnotations;
using System.Text;
using Microsoft.IdentityModel.Tokens;
namespace Chatex.Core.Auth;
/// <summary>Settings for access and refresh tokens, bound from the <c>Jwt</c> configuration section.</summary>
public sealed class JwtOptions
{
public const string Section = "Jwt";
[Required]
public string Issuer { get; set; } = "";
[Required]
public string Audience { get; set; } = "";
/// <summary>HMAC-SHA256 key, at least 32 characters. Keep it out of source control in production.</summary>
[Required]
[MinLength(32)]
public string SigningKey { get; set; } = "";
[Range(typeof(TimeSpan), "00:01:00", "1.00:00:00")]
public TimeSpan AccessTokenLifetime { get; set; } = TimeSpan.FromMinutes(15);
[Range(typeof(TimeSpan), "01:00:00", "365.00:00:00")]
public TimeSpan RefreshTokenLifetime { get; set; } = TimeSpan.FromDays(30);
/// <summary>The key both for signing (here) and for validating tokens (in the Api).</summary>
public SymmetricSecurityKey CreateSigningKey() => new(Encoding.UTF8.GetBytes(SigningKey));
}Sectionnames the configuration section ("Jwt"), so the binding and the documentation use one constant.[Required],[MinLength(32)],[Range(...)]are checked byValidateDataAnnotations()when the options are registered inAddCore(end of this topic). For HMAC-SHA256 a key must have at least 256 bits; 32 characters of UTF-8 are at least 32 bytes.TimeSpansettings are written as text in JSON ("00:15:00"); theRangeattribute withtypeof(TimeSpan)compares them as time spans.CreateSigningKeyturns the text key into the key object of the JWT library. The API calls the same method in topic 13 to verify tokens, so signing and verification cannot drift apart.
Step 4. The token service
Why. Creating tokens is a technical job with sharp edges (time stamps, claims, key handling, randomness). One small service does it, behind an interface, so the auth service stays readable and a test can check its output.
Do.
cs
using System.Buffers.Text;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using Chatex.Data.Entities;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
namespace Chatex.Core.Auth;
public sealed record AccessToken(string Token, DateTimeOffset ExpiresAt);
/// <summary>A new refresh token: <see cref="Token"/> goes to the client, only <see cref="Hash"/> is stored.</summary>
public sealed record NewRefreshToken(string Token, string Hash);
public interface ITokenService
{
AccessToken CreateAccessToken(User user);
NewRefreshToken CreateRefreshToken();
string HashRefreshToken(string token);
}
internal sealed class TokenService(IOptions<JwtOptions> options, TimeProvider timeProvider) : ITokenService
{
private readonly JsonWebTokenHandler _handler = new() { SetDefaultTimesOnTokenCreation = false };
public AccessToken CreateAccessToken(User user)
{
var jwt = options.Value;
var now = timeProvider.GetUtcNow();
var expiresAt = now + jwt.AccessTokenLifetime;
var token = _handler.CreateToken(new SecurityTokenDescriptor
{
Issuer = jwt.Issuer,
Audience = jwt.Audience,
IssuedAt = now.UtcDateTime,
NotBefore = now.UtcDateTime,
Expires = expiresAt.UtcDateTime,
Subject = new ClaimsIdentity(
[
new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName!),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
]),
SigningCredentials = new SigningCredentials(jwt.CreateSigningKey(), SecurityAlgorithms.HmacSha256),
});
return new AccessToken(token, expiresAt);
}
public NewRefreshToken CreateRefreshToken()
{
var token = Base64Url.EncodeToString(RandomNumberGenerator.GetBytes(32));
return new NewRefreshToken(token, HashRefreshToken(token));
}
public string HashRefreshToken(string token) =>
Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(token)));
}The access token:
JsonWebTokenHandleris the modern JWT handler ofMicrosoft.IdentityModel. It is created once per service; the service is registered as a singleton.SetDefaultTimesOnTokenCreation = falsestops the handler from stamping the times with the real clock. Chatex setsIssuedAt,NotBeforeandExpiresitself from the injectedTimeProvider, so a test with a fake clock gets tokens that agree with that clock.- Three claims:
sub(subject) — the user id, which the API reads on every request;unique_name— the user name, handy for logs;jti(JWT id) — a unique id of this token.
The refresh token:
RandomNumberGenerator.GetBytes(32)draws 256 random bits from the operating system's cryptographic generator — never useRandomfor secrets. Base64Url makes them a 43-character string that is safe in a cookie.HashRefreshTokenstores a SHA-256 hash as lower-case hex. Why a fast hash here, when passwords need a slow one? A password is short and guessable, so an attacker with the hashes tries millions of guesses; a slow algorithm makes each guess expensive. A refresh token has 256 random bits: there is nothing to guess, so a fast hash is enough to make a stolen database useless.NewRefreshTokenreturns both values: the token goes to the client once, the hash goes to the database.
Check
dotnet build succeeds. TokenService is internal and not registered yet; it is used by the auth service later in this topic.