0
0
AngularDebug / FixBeginner · 4 min read

How to Handle JWT Authentication in Angular: Fix and Best Practices

In Angular, handle JWT authentication by storing the token securely (usually in localStorage or sessionStorage) and attaching it to HTTP requests using an HttpInterceptor. This interceptor adds the Authorization header with the token, enabling secure API calls.
🔍

Why This Happens

Developers often try to manually add JWT tokens to HTTP requests without using Angular's HttpInterceptor. This causes repeated code and missed tokens on some requests, leading to unauthorized errors.

typescript
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class ApiService {
  constructor(private http: HttpClient) {}

  getData() {
    const token = localStorage.getItem('jwtToken');
    return this.http.get('https://api.example.com/data', {
      headers: { Authorization: 'Bearer ' + token }
    });
  }
}
Output
Error: 401 Unauthorized - Token missing or invalid on some requests
🔧

The Fix

Use an HttpInterceptor to automatically add the JWT token to all outgoing HTTP requests. This centralizes token handling and avoids missing tokens.

typescript
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HTTP_INTERCEPTORS } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = localStorage.getItem('jwtToken');
    if (token) {
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${token}`
        }
      });
    }
    return next.handle(request);
  }
}

// In app.module.ts, add JwtInterceptor to providers:
// { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true }
Output
HTTP requests include Authorization header with Bearer token; API calls succeed with valid JWT
🛡️

Prevention

Always use HttpInterceptor for token injection to avoid repeating code and missing tokens. Store JWT tokens securely and clear them on logout. Use Angular's HttpClient and handle errors globally to detect expired or invalid tokens.

  • Use localStorage or sessionStorage carefully, considering XSS risks.
  • Clear tokens on logout to prevent unauthorized access.
  • Use Angular guards to protect routes based on authentication state.
⚠️

Related Errors

Common related errors include:

  • 401 Unauthorized: Token missing or expired; fix by refreshing token or redirecting to login.
  • Token not attached: Happens if interceptor is not registered or token is null.
  • CORS errors: Ensure backend accepts Authorization headers.

Key Takeaways

Use Angular HttpInterceptor to add JWT tokens to all HTTP requests automatically.
Store JWT tokens securely and clear them on logout to protect user data.
Handle token expiration and errors globally for a smooth user experience.
Protect routes with Angular guards based on authentication state.
Avoid manual token handling in each service to reduce bugs and code duplication.