Overview
SAPFIAI uses JSON Web Tokens (JWT) for stateless authentication. The system implements secure token generation, validation, and a refresh token mechanism for extended sessions.JWT Token Generator
TheJwtTokenGenerator service handles all JWT operations:
Location: src/Infrastructure/Services/JwtTokenGenerator.cs
Token Configuration
JWT tokens are configured throughappsettings.json:
Token Generation
TheGenerateToken method creates JWT tokens with user information and claims:
sub(Subject): User IDemail: User emailjti(JWT ID): Unique token identifierNameIdentifier: User ID for ASP.NET Core Identity2fa_pending: Two-factor authentication statusrole: User roles (multiple claims)permission: User permissions (multiple claims)
Token Validation
TheValidateToken method verifies token signature, issuer, audience, and lifetime:
ValidateIssuerSigningKey: true (HMAC-SHA256)ValidateIssuer: trueValidateAudience: trueValidateLifetime: trueClockSkew: Zero (no tolerance for expired tokens)
Extracting Claims
Utility methods for extracting information from tokens:Refresh Token Mechanism
The refresh token system allows users to obtain new access tokens without re-authenticating.RefreshToken Entity
Location:src/Domain/Entities/RefreshToken.cs
RefreshTokenService
Location:src/Infrastructure/Services/RefreshTokenService.cs
Configuration
Generating Refresh Tokens
- Generates cryptographically secure 64-byte token
- Automatically revokes oldest token if user exceeds max active tokens
- Associates token with IP address for security tracking
Validating Refresh Tokens
- Token exists in database
- Token is not revoked
- Token is not expired
- Associated user still exists
Revoking Tokens
Revoke single token:Managing Active Tokens
Get active tokens for user:API Endpoints
Login
Refresh Token
Revoke Token
Security Best Practices
Token Storage
- Access tokens: Store in memory (React state, Vue store) - never in localStorage
- Refresh tokens: Store in httpOnly cookies or secure storage
- Never expose tokens in URLs or logs
Token Rotation
- Refresh tokens are single-use when configured
- New refresh token issued with each access token refresh
- Old refresh token automatically revoked
Token Revocation
- All tokens revoked on password change
- Manual revocation available through API
- Automatic cleanup of expired tokens
Security Headers
Always validate tokens on the server side:Implementation Details
File locations:- JWT Generator:
src/Infrastructure/Services/JwtTokenGenerator.cs:11 - Refresh Token Service:
src/Infrastructure/Services/RefreshTokenService.cs:9 - RefreshToken Entity:
src/Domain/Entities/RefreshToken.cs:3 - Login Endpoint:
src/Web/Endpoints/Authentication.cs:112 - Refresh Endpoint:
src/Web/Endpoints/Authentication.cs:169 - Revoke Endpoint:
src/Web/Endpoints/Authentication.cs:198