.NET MAUI › Networking & APIs
How do you implement authentication token refresh transparently for API calls?
AdvancedAnswer
Use a DelegatingHandler in the HttpClient pipeline that attaches the access token, detects 401 responses, refreshes the token (serialized with a lock/semaphore to avoid stampedes), and retries the request. Store tokens in SecureStorage. This centralizes auth so callers stay unaware.
class AuthHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage req, CancellationToken ct)
{
req.Headers.Authorization = new("Bearer", await _tokens.GetAsync());
var res = await base.SendAsync(req, ct);
// on 401: refresh + retry
return res;
}
}Real-world example Expired tokens refresh silently mid-session so users are never bounced to the login screen during normal use.