Overview
TheTokenStorageService is a utility service that manages JWT (JSON Web Token) authentication tokens in the browser’s localStorage. It provides methods to save, retrieve, and remove tokens, as well as check authentication status.
Location: src/app/core/services/token-storage.service.ts
Constructor
window.localStorage API.
Constants
string
default:"'auth-token'"
The localStorage key used to store the JWT token
Methods
saveToken()
Saves the JWT token to localStorage.string
required
The JWT token string to store
void
Behavior:
- Removes any existing token from localStorage
- Saves the new token to localStorage with key
'auth-token'
getToken()
Retrieves the JWT token from localStorage.string | null - The stored JWT token, or null if not found
Example:
- Retrieving token for HTTP request headers
- Checking if user is logged in
- Used by AuthInterceptor to add token to API requests
signOut()
Removes the JWT token from localStorage, effectively logging out the user.void
Behavior: Removes the token from localStorage using the TOKEN_KEY
Example:
isLoggedIn()
Checks whether a user is currently authenticated.boolean - true if token exists, false otherwise
Implementation: Returns true if getToken() returns a non-null value
Example:
- Route guards to protect authenticated pages
- Conditional UI rendering
- Navigation logic
Complete Usage Example
Integration with AuthService
Use in HTTP Interceptor
Use in Route Guard
Security Considerations
localStorage vs sessionStorage
This service useslocalStorage which persists across browser sessions. Consider these security implications:
Advantages:
- Token persists across browser restarts
- Better user experience (stay logged in)
- Vulnerable to XSS attacks if application has XSS vulnerabilities
- Token persists until explicitly removed
Best Practices
- Token Expiration: Implement token refresh logic before expiration
- XSS Protection: Sanitize all user inputs to prevent XSS attacks
- HTTPS Only: Always use HTTPS in production to prevent token interception
- Automatic Logout: Clear tokens on security-sensitive errors (401, 403)
Token Format
The service stores JWT tokens in standard format:- Header: Algorithm and token type
- Payload: User data and claims
- Signature: Verification signature
Debugging
Inspect tokens in browser developer tools:Common Patterns
Checking Authentication Before Navigation
Conditional Template Rendering
See Also
- AuthService - Uses TokenStorageService for authentication
- AuthInterceptor - Adds tokens to HTTP requests
- AuthGuard - Protects routes using token validation