Angular JWT Security

Learn Angular JWT Security with JWT structure, authentication flow, access tokens, refresh tokens, Http Interceptors, route guards, secure storage, token refresh, OWASP best practices, and interview questions.

JSON Web Token (JWT) is one of the most widely used authentication mechanisms for modern web applications and REST APIs.

Angular applications commonly use JWTs to authenticate users and securely access protected backend APIs.

A secure JWT implementation involves much more than simply storing a token. It includes:

  • Authentication
  • Authorization
  • Secure token storage
  • Token expiration
  • Refresh tokens
  • HTTP Interceptors
  • Route Guards
  • HTTPS
  • Backend validation

This guide explains JWT security from beginner to enterprise level.


Table of Contents

  1. What is JWT?
  2. Why JWT?
  3. JWT Structure
  4. Authentication Flow
  5. Access Token vs Refresh Token
  6. HTTP Interceptor
  7. Route Guards
  8. Token Refresh
  9. Secure Token Storage
  10. Enterprise Banking Example
  11. Best Practices
  12. Common Mistakes
  13. Top 10 Interview Questions
  14. Interview Cheat Sheet
  15. Summary

What is JWT?

A JSON Web Token (JWT) is a compact, digitally signed token used to securely transmit identity and authorization information between a client and a server.

JWTs are:

  • Compact
  • URL-safe
  • Digitally signed
  • Stateless
  • Widely supported

JWT is commonly used with:

  • REST APIs
  • OAuth 2.0
  • OpenID Connect (OIDC)
  • Single Page Applications (SPAs)

Why Use JWT?

Benefits include:

  • Stateless authentication
  • No server-side session storage required
  • Easy scaling
  • Fast API authentication
  • Cross-platform support
  • Mobile friendly

JWT Structure

A JWT contains three parts.

HEADER

.

PAYLOAD

.

SIGNATURE

Example

xxxxx.yyyyy.zzzzz

JWT Components

Contains metadata.

{
  "alg": "HS256",
  "typ": "JWT"
}

Payload

Contains claims.

{
  "sub": "1001",
  "name": "John Doe",
  "role": "ADMIN",
  "exp": 1799999999
}

Common claims

  • sub
  • iss
  • aud
  • exp
  • iat
  • nbf
  • jti

Signature

Generated using:

  • Header
  • Payload
  • Secret key or private key

The signature protects against tampering.


JWT Architecture

flowchart LR

User

User --> Login

Login --> AuthAPI

AuthAPI --> JWT

JWT --> Angular

Angular --> BackendAPI

BackendAPI --> Response

Authentication Flow

sequenceDiagram

participant User

participant Angular

participant AuthAPI

User->>Angular: Login

Angular->>AuthAPI: Username + Password

AuthAPI-->>Angular: JWT

Angular->>AuthAPI: API Request

Note right of Angular: Authorization: Bearer Token

AuthAPI-->>Angular: Protected Data

Authorization Header

Angular sends JWT using the Authorization header.

Authorization:

Bearer eyJhbGciOi...

The backend validates:

  • Signature
  • Expiration
  • Issuer
  • Audience
  • User permissions

Access Token vs Refresh Token

Feature Access Token Refresh Token
Lifetime Short Longer
API Access Yes No
Used Frequently Yes Only for renewal
Security Risk Lower Higher
Rotation Recommended Yes Yes

Token Lifecycle

flowchart LR

Login

Login --> AccessToken

AccessToken --> API

AccessToken --> Expired

Expired --> RefreshToken

RefreshToken --> NewAccessToken

NewAccessToken --> API

HTTP Interceptor

Attach JWT automatically.

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ) {

    const token = this.authService.getAccessToken();

    if (!token) {
      return next.handle(request);
    }

    const authRequest = request.clone({
      setHeaders: {
        Authorization: `Bearer ${token}`
      }
    });

    return next.handle(authRequest);

  }

}

Benefits

  • Centralized authentication
  • Less duplicate code
  • Cleaner services

Route Guards

Protect application routes.

export const authGuard: CanActivateFn = () => {

  const authService = inject(AuthService);

  return authService.isAuthenticated();

};

Routes

{
  path: 'dashboard',
  canActivate: [authGuard],
  loadComponent: () =>
    import('./dashboard.component')
}

Route Guards improve navigation but do not replace backend authorization.


Token Refresh

When an access token expires:

  1. API returns 401 Unauthorized
  2. Refresh token is sent to the authentication server
  3. Server validates refresh token
  4. New access token is issued
  5. Original request is retried

Refresh Flow

sequenceDiagram

participant Angular

participant API

participant AuthServer

Angular->>API: Access Token

API-->>Angular: 401 Unauthorized

Angular->>AuthServer: Refresh Token

AuthServer-->>Angular: New Access Token

Angular->>API: Retry Request

API-->>Angular: Success

Secure Token Storage

Common options

Storage Recommendation
HttpOnly Secure Cookie Preferred for many web applications
Memory Good for short-lived access tokens
localStorage Use only after understanding the security trade-offs
sessionStorage Better than persistent storage for some use cases, but still accessible to JavaScript

Whenever possible:

  • Use HttpOnly cookies for sensitive tokens
  • Keep access tokens short-lived
  • Protect against XSS

Token Expiration

Access tokens should have:

  • Short lifetime
  • Automatic refresh
  • Proper logout
  • Revocation support where applicable

Short-lived tokens reduce the impact of token theft.


JWT Claims

Claim Purpose
sub Subject
iss Issuer
aud Audience
exp Expiration
iat Issued At
nbf Not Before
jti Token Identifier

Enterprise Banking Example

A banking platform secures:

  • Customer Dashboard
  • Account Details
  • Transfers
  • Loans
  • Investments
  • Credit Cards

Architecture

flowchart TD

Customer

Customer --> Login

Login --> AuthServer

AuthServer --> AccessToken

AccessToken --> Angular

Angular --> Interceptor

Interceptor --> BankingAPI

BankingAPI --> Validation

Validation --> BankingServices

Security Layers

  • HTTPS
  • JWT
  • Refresh Tokens
  • Http Interceptors
  • Route Guards
  • Backend Authorization
  • Audit Logging

Performance Best Practices

Practice Benefit
Short-lived Access Tokens Better security
Refresh Tokens Better user experience
HTTP Interceptors Centralized authentication
Route Guards Protected navigation
HTTPS Secure communication
Backend Validation Defense in depth
Token Rotation Reduced replay risk
Minimal Claims Smaller tokens

Common Mistakes

Storing Sensitive Tokens In Insecure Locations

Avoid storing long-lived or highly sensitive tokens in browser storage unless you fully understand the security implications.


Trusting JWT Without Validation

Always validate:

  • Signature
  • Expiration
  • Issuer
  • Audience
  • User permissions

Long-Lived Access Tokens

Avoid access tokens that remain valid for long periods.

Prefer:

  • Short expiration
  • Refresh tokens

Depending Only on Route Guards

Route Guards improve the user experience but cannot secure backend APIs.

Every protected endpoint must validate authentication and authorization.


Sending Tokens Over HTTP

Always use HTTPS in production.


JWT Security Best Practices

Practice Benefit
HTTPS Secure transport
Short-lived Access Tokens Lower risk
Refresh Tokens Better UX
Validate JWT Prevent misuse
Rotate Refresh Tokens Improved security
HTTP Interceptors Automatic headers
Route Guards Navigation security
Backend Authorization API protection
Audit Logging Compliance
Follow OWASP Enterprise security

JWT vs Session Authentication

Feature JWT Session
Stateless
Server Session
Scalable Excellent Moderate
Mobile Friendly Excellent Good
Token Based
Cookie Based Optional Yes

Top 10 JWT Security Interview Questions

1. What is JWT?

Answer

JWT (JSON Web Token) is a compact, digitally signed token used to securely transmit identity and authorization information between a client and a server.


2. What are the three parts of a JWT?

Answer

A JWT consists of:

  • Header
  • Payload
  • Signature

3. What is the difference between an Access Token and a Refresh Token?

Answer

An access token is used to call protected APIs and typically has a short lifetime. A refresh token is used to obtain new access tokens without requiring the user to log in again.


4. Why use HTTP Interceptors with JWT?

Answer

Interceptors automatically attach authorization headers to outgoing requests and centralize authentication-related HTTP logic.


5. Can Route Guards secure APIs?

Answer

No. Route Guards only protect client-side navigation. Every backend API must independently validate authentication and authorization.


6. Why should access tokens expire quickly?

Answer

Short-lived access tokens reduce the window of opportunity if a token is stolen.


7. What information does a JWT payload contain?

Answer

The payload contains claims such as the user identifier, issuer, audience, expiration time, and application-specific information.


8. Should JWTs always be encrypted?

Answer

Standard JWTs (JWS) are typically signed, not encrypted. If confidentiality is required, encrypted JWTs (JWE) or transport encryption with HTTPS may be appropriate depending on the use case.


9. What are JWT security best practices?

Answer

  • Use HTTPS
  • Validate tokens on the server
  • Use short-lived access tokens
  • Rotate refresh tokens
  • Minimize claims
  • Protect against XSS
  • Follow OWASP recommendations

10. What are common JWT implementation mistakes?

Answer

  • Long-lived access tokens
  • Skipping signature validation
  • Storing sensitive tokens insecurely
  • Relying only on Route Guards
  • Ignoring backend authorization

Interview Cheat Sheet

Requirement Recommended Solution
Authentication JWT
Authorization Backend Validation
Automatic Headers HTTP Interceptor
Route Protection Route Guards
Token Renewal Refresh Token
Secure Transport HTTPS
Secure Storage HttpOnly Cookies (when applicable)
Token Lifetime Short
Enterprise Security OWASP
Production HTTPS + Token Validation + Refresh

Summary

JWT is a scalable and widely adopted authentication mechanism for Angular applications. A secure implementation combines short-lived access tokens, refresh tokens, HTTPS, HTTP Interceptors, backend authorization, and proper token validation. While Angular simplifies client-side integration, true JWT security depends on a defense-in-depth approach that includes both frontend and backend protections.


Key Takeaways

  • ✅ JWT consists of Header, Payload, and Signature.
  • ✅ Access tokens should have short lifetimes.
  • ✅ Refresh tokens improve user experience while maintaining security.
  • ✅ HTTP Interceptors centralize authentication logic.
  • ✅ Route Guards protect navigation but not backend APIs.
  • ✅ Always validate JWTs on the server.
  • ✅ Use HTTPS for all authenticated communication.
  • ✅ Minimize the information stored in JWT claims.
  • ✅ Follow OWASP recommendations for secure authentication.
  • ✅ JWT security is one of the most frequently asked Angular interview topics.

Next Article

➡️ 108-OAuth2-and-OpenID-Connect-QA.md