English
The authentication service
Step 1. The interface
Why. The interface is the contract the API will call. Its comments state the rules that are not obvious from the names: registration signs the user in; a refresh token works once; reusing one ends every session; sign-out succeeds even with an unknown token (a client that signs out twice is not an error).
Step 2. Rotation and theft detection
Why. A refresh token lives 30 days, which makes it a valuable target. Chatex limits the damage of a stolen token with rotation (Fig. 8.2): every refresh revokes the presented token and issues a new one. The legitimate browser and a thief now hold copies of the same token; whoever uses it first gets a new pair, and when the other one presents the old token, it is already revoked. A revoked token that comes back can only mean that two parties had it — so the service revokes every session of the user, and both have to sign in again with the password, which the thief does not have.
Fig. 8.2. Rotation of refresh tokens and detection of reuse
Step 3. The service
Do.
cs
using Chatex.Core.Common;
using Chatex.Core.Users;
using Chatex.Data.Abstractions;
using Chatex.Data.Entities;
using FluentValidation;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
namespace Chatex.Core.Auth;
public interface IAuthService
{
/// <summary>Creates the account and its profile, and signs the new user in.</summary>
Task<Result<AuthResult>> RegisterAsync(RegisterCommand command, ClientInfo client, CancellationToken cancellationToken = default);
Task<Result<AuthResult>> LoginAsync(LoginCommand command, ClientInfo client, CancellationToken cancellationToken = default);
/// <summary>
/// Exchanges a refresh token for a new token pair. Each refresh token works once; presenting a used one
/// signs the user out everywhere, because it means the token was stolen.
/// </summary>
Task<Result<AuthResult>> RefreshAsync(RefreshCommand command, ClientInfo client, CancellationToken cancellationToken = default);
/// <summary>Ends one session. Succeeds even if the token is unknown or already revoked.</summary>
Task<Result> LogoutAsync(RefreshCommand command, CancellationToken cancellationToken = default);
/// <summary>Ends every session of the user.</summary>
Task<Result> LogoutAllAsync(Guid userId, CancellationToken cancellationToken = default);
/// <summary>
/// Deletes refresh tokens that expired or were revoked more than one refresh token lifetime ago; returns how many.
/// Revoked tokens stay that long so a stolen token that comes back still signs the user out everywhere.
/// </summary>
Task<int> DeleteStaleRefreshTokensAsync(CancellationToken cancellationToken = default);
}
internal sealed class AuthService(
UserManager<User> userManager,
IUserRepository users,
IRefreshTokenRepository refreshTokens,
IUnitOfWork unitOfWork,
ITokenService tokens,
IOptions<JwtOptions> jwtOptions,
TimeProvider timeProvider,
IValidator<RegisterCommand> registerValidator,
IValidator<LoginCommand> loginValidator) : IAuthService
{
private const int MaxUserAgentLength = 512;
private const int MaxIpLength = 45;
public async Task<Result<AuthResult>> RegisterAsync(
RegisterCommand command, ClientInfo client, CancellationToken cancellationToken = default)
{
if (await registerValidator.ValidateToErrorAsync(command, cancellationToken) is { } invalid)
{
return invalid;
}
var user = new User { UserName = command.UserName.ToLowerInvariant(), Email = command.Email.Trim() };
return await unitOfWork.ExecuteInTransactionAsync<Result<AuthResult>>(async ct =>
{
var created = await userManager.CreateAsync(user, command.Password);
if (!created.Succeeded)
{
return ToError(created.Errors);
}
users.AddProfile(new UserProfile { UserId = user.Id, DisplayName = command.DisplayName.Trim() });
return await IssueTokensAsync(user, client, ct);
}, cancellationToken);
}
public async Task<Result<AuthResult>> LoginAsync(
LoginCommand command, ClientInfo client, CancellationToken cancellationToken = default)
{
if (await loginValidator.ValidateToErrorAsync(command, cancellationToken) is { } invalid)
{
return invalid;
}
var login = command.Login.Trim();
var user = login.Contains('@')
? await userManager.FindByEmailAsync(login)
: await userManager.FindByNameAsync(login);
if (user is null)
{
return AuthErrors.InvalidCredentials;
}
if (await userManager.IsLockedOutAsync(user))
{
return AuthErrors.LockedOut;
}
if (!await userManager.CheckPasswordAsync(user, command.Password))
{
await userManager.AccessFailedAsync(user);
return await userManager.IsLockedOutAsync(user) ? AuthErrors.LockedOut : AuthErrors.InvalidCredentials;
}
await userManager.ResetAccessFailedCountAsync(user);
return await IssueTokensAsync(user, client, cancellationToken);
}
public async Task<Result<AuthResult>> RefreshAsync(
RefreshCommand command, ClientInfo client, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(command.RefreshToken))
{
return AuthErrors.InvalidRefreshToken;
}
var now = timeProvider.GetUtcNow();
var current = await refreshTokens.GetByHashAsync(tokens.HashRefreshToken(command.RefreshToken), cancellationToken);
if (current is null || current.ExpiresAt <= now)
{
return AuthErrors.InvalidRefreshToken;
}
if (current.RevokedAt is not null)
{
// A used token came back: someone else holds a copy. End every session of this user.
await refreshTokens.RevokeAllForUserAsync(current.UserId, now, cancellationToken);
return AuthErrors.InvalidRefreshToken;
}
current.RevokedAt = now;
return await IssueTokensAsync(current.User, client, cancellationToken, replaces: current);
}
public async Task<Result> LogoutAsync(RefreshCommand command, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(command.RefreshToken))
{
return Result.Success;
}
var token = await refreshTokens.GetByHashAsync(tokens.HashRefreshToken(command.RefreshToken), cancellationToken);
if (token is { RevokedAt: null })
{
token.RevokedAt = timeProvider.GetUtcNow();
await unitOfWork.SaveChangesAsync(cancellationToken);
}
return Result.Success;
}
public async Task<Result> LogoutAllAsync(Guid userId, CancellationToken cancellationToken = default)
{
await refreshTokens.RevokeAllForUserAsync(userId, timeProvider.GetUtcNow(), cancellationToken);
return Result.Success;
}
public Task<int> DeleteStaleRefreshTokensAsync(CancellationToken cancellationToken = default) =>
refreshTokens.DeleteStaleAsync(timeProvider.GetUtcNow() - jwtOptions.Value.RefreshTokenLifetime, cancellationToken);
/// <summary>Stores a new refresh token (linking it from <paramref name="replaces"/>), saves, and returns both tokens.</summary>
private async Task<AuthResult> IssueTokensAsync(
User user, ClientInfo client, CancellationToken cancellationToken, RefreshToken? replaces = null)
{
var now = timeProvider.GetUtcNow();
var access = tokens.CreateAccessToken(user);
var refresh = tokens.CreateRefreshToken();
var entity = new RefreshToken
{
UserId = user.Id,
TokenHash = refresh.Hash,
ExpiresAt = now + jwtOptions.Value.RefreshTokenLifetime,
UserAgent = Truncate(client.UserAgent, MaxUserAgentLength),
CreatedByIp = Truncate(client.IpAddress, MaxIpLength),
};
refreshTokens.Add(entity);
if (replaces is not null)
{
replaces.ReplacedByTokenId = entity.Id;
}
await unitOfWork.SaveChangesAsync(cancellationToken);
// Loads the profile into the tracked user for the response.
var withProfile = await users.GetWithProfileAsync(user.Id, cancellationToken) ?? user;
return new AuthResult(access.Token, access.ExpiresAt, refresh.Token, entity.ExpiresAt, withProfile.ToMyProfileDto());
}
private static Error ToError(IEnumerable<IdentityError> errors)
{
var list = errors.ToList();
if (list.Any(e => e.Code == nameof(IdentityErrorDescriber.DuplicateUserName)))
{
return AuthErrors.UserNameTaken;
}
if (list.Any(e => e.Code == nameof(IdentityErrorDescriber.DuplicateEmail)))
{
return AuthErrors.EmailTaken;
}
return IdentityErrors.ToValidationError(list);
}
private static string? Truncate(string? value, int maxLength) =>
value?.Length > maxLength ? value[..maxLength] : value;
}Registration
- The command is validated first; an invalid command never touches the database.
- The user name is lower-cased:
Aliceandaliceare the same handle. The email is trimmed. ExecuteInTransactionAsync<Result<AuthResult>>runs the whole registration in one transaction (topic 5):UserManager.CreateAsyncsaves the user, then the profile and the first refresh token are saved byIssueTokensAsync. If any step fails — even with an expected error returned as a result — nothing must remain. The type argument is written out because the lambda returns bothErrorandAuthResultvalues, and the compiler needs to know that they meanResult<AuthResult>.ToErrorturns Identity's failures into our errors:DuplicateUserNameandDuplicateEmailbecome conflicts, everything else (weak password, invalid characters) one validation error with per-field details fromIdentityErrors(topic 7).nameof(IdentityErrorDescriber.DuplicateUserName)gives the code as a string without a magic literal.
A fair question: when the lambda returns an error instead of throwing, is the transaction rolled back? No — ExecuteInTransactionAsync commits whenever the lambda returns normally. On a failed CreateAsync, Identity has saved nothing, so there is nothing to roll back. Later failures inside IssueTokensAsync are exceptions (a lost connection), which roll the transaction back.
Sign-in
- Name or email: a login with
@is looked up by email, otherwise by user name. - The order of the checks matters. An unknown user gets
invalid_credentials. A locked-out user getslocked_outbefore the password is checked, so a locked account cannot be used to test passwords. A wrong password counts a failure withAccessFailedAsync; the fifth failure locks the account for 15 minutes (the options are set inAddCorebelow), and the answer becomeslocked_outright away. - A correct password resets the failure counter and issues tokens.
Refresh
- The token is looked up by its hash; the plain token never reaches the database.
- An unknown or expired token:
invalid_refresh_token. - A revoked token: theft (Fig. 8.2) —
RevokeAllForUserAsyncends every session, and the answer is the same vague error. - Otherwise the token is revoked (
current.RevokedAt = now) and a new pair is issued;IssueTokensAsynclinks the old token to its successor withReplacedByTokenIdand saves both changes in oneSaveChangesAsync.
Sign-out and cleanup
LogoutAsyncrevokes one token if it is active. The property patterntoken is { RevokedAt: null }means "not null, and not revoked yet".LogoutAllAsyncrevokes all tokens of the user (the settings page offers "sign out everywhere").DeleteStaleRefreshTokensAsyncdeletes tokens that expired or were revoked more than a full refresh lifetime ago. A revoked token must stay that long: until it would have expired anyway, its return must still be recognised as theft. The hourly maintenance job of topic 13 calls it.
Issuing tokens
IssueTokensAsync is the one place where sessions start. The user agent and the IP are cut to the column lengths of topic 4 with Truncate — value[..maxLength] is a range on a string. After saving, the user is loaded with the profile, because UserManager returned the user without it, and the result needs the display name.
Step 4. Register the services
Why. The auth service needs Identity's UserManager (registered by AddData), the token service, the validators and the two kinds of settings: the JWT options and Identity's own options — the password rules and the lockout.
Do. Extend AddCore (new lines in green):
cs
using Chatex.Core.Auth;
using Chatex.Data;
using FluentValidation;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Chatex.Core;
public static class DependencyInjection
{
public static IServiceCollection AddCore(this IServiceCollection services, IConfiguration configuration)
{
var connectionString = configuration.GetConnectionString("Chatex")
?? throw new InvalidOperationException("Connection string 'Chatex' is not configured.");
services.AddData(connectionString, o => o.RootPath = configuration["Storage:RootPath"] ?? "");
services.AddOptions<JwtOptions>()
.Bind(configuration.GetSection(JwtOptions.Section))
.ValidateDataAnnotations()
.ValidateOnStart();
services.Configure<IdentityOptions>(o =>
{
o.User.RequireUniqueEmail = true;
o.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyz0123456789_";
o.Password.RequiredLength = 8;
o.Password.RequireDigit = true;
o.Password.RequireLowercase = false;
o.Password.RequireUppercase = false;
o.Password.RequireNonAlphanumeric = false;
o.Lockout.MaxFailedAccessAttempts = 5;
o.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
});
services.AddValidatorsFromAssemblyContaining<AuthService>(includeInternalTypes: true);
services.AddSingleton<ITokenService, TokenService>();
services.AddScoped<IAuthService, AuthService>();
return services;
}
}AddOptions<JwtOptions>().Bind(...).ValidateDataAnnotations().ValidateOnStart()binds theJwtsection, checks the attributes ofJwtOptionsand does so when the application starts. A missing signing key stops the start with a message that names the property.Configure<IdentityOptions>sets Identity's rules: unique emails; user names of lower-case letters, digits and underscores (the service lower-cases the name first); passwords of at least 8 characters with a digit — length beats complexity rules; 5 failed attempts lock the account for 15 minutes.AddValidatorsFromAssemblyContaining<AuthService>(includeInternalTypes: true)finds everyAbstractValidator<T>in Chatex.Core and registers it asIValidator<T>. Our validators areinternal, henceincludeInternalTypes. Every validator of later topics is registered by this one line.ITokenServiceis a singleton: it keeps no per-request state.IAuthServiceis scoped, like the repositories and the context it uses.
Check
dotnet build succeeds. The service is complete; the next chapter proves it.