Skip to main content

Overview

The TokenStorageService 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

No dependencies required. Uses browser’s native 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
Returns: void Behavior:
  1. Removes any existing token from localStorage
  2. Saves the new token to localStorage with key 'auth-token'
Example:
Use Case: Called by AuthService after successful login

getToken()

Retrieves the JWT token from localStorage.
Returns: string | null - The stored JWT token, or null if not found Example:
Use Case:
  • 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.
Returns: void Behavior: Removes the token from localStorage using the TOKEN_KEY Example:
Use Case: Called by AuthService.logout() to clear authentication data

isLoggedIn()

Checks whether a user is currently authenticated.
Returns: boolean - true if token exists, false otherwise Implementation: Returns true if getToken() returns a non-null value Example:
Use Case:
  • 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 uses localStorage which persists across browser sessions. Consider these security implications: Advantages:
  • Token persists across browser restarts
  • Better user experience (stay logged in)
Disadvantages:
  • Vulnerable to XSS attacks if application has XSS vulnerabilities
  • Token persists until explicitly removed
Alternative Implementation with sessionStorage:

Best Practices

  1. Token Expiration: Implement token refresh logic before expiration
  2. XSS Protection: Sanitize all user inputs to prevent XSS attacks
  3. HTTPS Only: Always use HTTPS in production to prevent token interception
  4. Automatic Logout: Clear tokens on security-sensitive errors (401, 403)

Token Format

The service stores JWT tokens in standard format:
The token consists of three parts separated by dots:
  1. Header: Algorithm and token type
  2. Payload: User data and claims
  3. Signature: Verification signature

Debugging

Inspect tokens in browser developer tools:

Common Patterns

Checking Authentication Before Navigation

Conditional Template Rendering

See Also