JWT authentication is popular in modern single-page applications like Angular because it is simple and stateless. However, one common requirement is enforcing auto logout when the token expires. This prevents unauthorized access and improves application security.

In this article, you will learn:

Everything is explained in simple language with full practical code.

Understanding Token Expiration

A JWT includes an expiration time:

exp: 1712345123

Once this time is reached:

Token expiration is important for security because it prevents tokens from being used forever.

Part 1: Backend Setup (ASP.NET Core)

We assume you already have a JWT configuration.
Here we only focus on enabling proper token expiration.

Step 1: Add Expiration to Token

In your JWT service (JwtService.cs):

public string GenerateToken(string email)
{
    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

    var claims = new[]
    {
        new Claim(ClaimTypes.Email, email)
    };

    var token = new JwtSecurityToken(
        issuer: _config["Jwt:Issuer"],
        audience: _config["Jwt:Audience"],
        claims: claims,
        expires: DateTime.Now.AddMinutes(30),   // Token expires in 30 minutes
        signingCredentials: creds);

    return new JwtSecurityTokenHandler().WriteToken(token);
}

The important part:

expires: DateTime.Now.AddMinutes(30)

The token now carries a clear expiration time.

Part 2: Angular Frontend Setup

The entire auto logout mechanism happens on the Angular side.

We need:

  1. Decode token

  2. Extract expiration time

  3. Compare expiration time with current time

  4. Automatically log out the user when expired

  5. Intercept expired tokens in API calls

Let’s implement these step by step.

Step 1: Install JWT Helper Library

This library allows easy decoding of JWT tokens:

npm install jwt-decode

Step 2: Update AuthService

File: auth.service.ts

This service will:

Import jwtDecode

import jwtDecode from 'jwt-decode';

Full AuthService with expiration check

import { Injectable } from '@angular/core';
import jwtDecode from 'jwt-decode';
import { Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  constructor(private router: Router) {}

  saveToken(token: string) {
    localStorage.setItem('token', token);
    this.startAutoLogout();
  }

  getToken() {
    return localStorage.getItem('token');
  }

  logout() {
    localStorage.removeItem('token');
    this.router.navigate(['/login']);
  }

  isLoggedIn(): boolean {
    const token = this.getToken();
    if (!token) return false;

    const decoded: any = jwtDecode(token);
    const exp = decoded.exp * 1000;
    return Date.now() < exp;
  }

  startAutoLogout() {
    const token = this.getToken();
    if (!token) return;

    const decoded: any = jwtDecode(token);
    const exp = decoded.exp * 1000;

    const timeout = exp - Date.now(); // time left in ms

    if (timeout > 0) {
      setTimeout(() => {
        this.logout();
      }, timeout);
    } else {
      this.logout();
    }
  }
}

What happens here?

Step 3: Start Auto Logout When App Loads

In app.component.ts:

constructor(private auth: AuthService) {}

ngOnInit() {
  this.auth.startAutoLogout();
}

Now whenever Angular loads, it checks the token and sets auto logout.

Step 4: Auto Logout When API Returns 401

Sometimes backend returns 401 Unauthorized (expired token).
We catch this using HttpInterceptor.

Create:

ng generate interceptor auth-expired

In auth-expired.interceptor.ts:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpErrorResponse } from '@angular/common/http';
import { AuthService } from './auth.service';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

@Injectable()
export class AuthExpiredInterceptor implements HttpInterceptor {

  constructor(private auth: AuthService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler) {
    return next.handle(req).pipe(
      catchError((error: HttpErrorResponse) => {

        if (error.status === 401) {
          this.auth.logout();
        }

        return throwError(() => error);
      })
    );
  }
}

Add this to app.module.ts:

{
  provide: HTTP_INTERCEPTORS,
  useClass: AuthExpiredInterceptor,
  multi: true
}

Step 5: Protect Routes Using AuthGuard

This ensures expired users cannot access protected pages.

ng generate guard auth

In auth.guard.ts:

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  constructor(private auth: AuthService, private router: Router) {}

  canActivate() {
    if (this.auth.isLoggedIn()) {
      return true;
    }
    this.router.navigate(['/login']);
    return false;
  }
}

Use in routing:

{
  path: 'dashboard',
  component: DashboardComponent,
  canActivate: [AuthGuard]
}

Full Flow Summary

Here is what now happens:

Login

  1. User logs in

  2. API returns JWT with expiration

  3. Angular saves token

  4. Angular sets auto logout timer

During App Usage

  1. Angular checks expiration regularly

  2. If token is expired, user is logged out automatically

  3. If a protected API call fails with 401, interceptor logs out the user

Visiting Protected Pages

  1. AuthGuard checks token validity

  2. If expired → redirect to login

This ensures full security.

Practical Example: Testing Auto Logout

Assume token includes:

Run Angular:

  1. Login

  2. Wait 10 minutes

  3. Angular auto logs you out

  4. You are redirected to login page

If you try to open:

/dashboard

You will be redirected because the token is expired.

Extra Enhancement: Show Expiration Warning

You can show a popup 1 minute before logout:

setTimeout(() => {
  alert("Your session will expire soon.");
}, timeout - 60000);

Let me know if you want this added to the article.

Extra Enhancement: Refresh Tokens

A refresh token system makes sure users do not log out frequently.

I can write:

Ask if needed.

Conclusion

In this article, you learned a complete and practical method for implementing auto logout after token expiration using Angular and ASP.NET Core JWT.

You now have:

This solution is production-ready and follows best security practices.