Token Management
Best practices for token management and handling authentication errors
Token Caching
Recommended Strategy
public class TokenCache
{
private string _token;
private DateTime _expiry;
private readonly SemaphoreSlim _lock = new(1, 1);
public async Task<string> GetTokenAsync(Func<Task<TokenResponse>> requestToken)
{
// Check if token is valid (with 5-minute buffer)
if (!string.IsNullOrEmpty(_token) && DateTime.UtcNow < _expiry.AddMinutes(-5))
{
return _token;
}
await _lock.WaitAsync();
try
{
// Double-check after acquiring lock
if (!string.IsNullOrEmpty(_token) && DateTime.UtcNow < _expiry.AddMinutes(-5))
{
return _token;
}
var response = await requestToken();
_token = response.AccessToken;
_expiry = DateTime.UtcNow.AddSeconds(response.ExpiresIn);
return _token;
}
finally
{
_lock.Release();
}
}
}Why Cache Tokens?
Without Caching
With Caching
Token Refresh Strategies
Proactive Refresh
Reactive Refresh
Security Best Practices
1. Secure Credential Storage
Environment
Storage Method
2. Use HTTPS Only
3. Validate Token Responses
4. Implement Token Isolation
5. Log Authentication Events
Error Handling
Token Request Errors
Error
Cause
Solution
API Authentication Errors
Status
Meaning
Action
Retry Logic
Troubleshooting
"invalid_client" Error
"invalid_scope" Error
Token Works in Postman but Not in Code
401 Errors After Token Refresh
Intermittent Authentication Failures
Complete Example
Last updated

