How to Use Cookie Storage with angular-auth-oidc-client in Angular 20 for Secure Token Management?How to Use Cookie Storage with angular-auth-oidc-client in Angular 20 for Secure Token Management?

Hello friends, welcome back to my blog. Today this blog post I will tell you How to Use Cookie Storage with angular-auth-oidc-client in Angular 20 for Secure Token Management?

Angular 20 came and if you are new then you must check below two links:

  1. Angular20Basic Tutorials
  2. Angular Admin Free Templates

Friends now I proceed onwards and here is the working code snippet for Angular 20 Authentication, angular-auth-oidc-client cookie storage, Secure token storage in Angular, Angular cookie-based authentication, Angular OIDC secure login, angular-auth-oidc-client tutorial 2025, Store tokens in cookies Angular, Angular login with OpenID Connect and please use carefully this to avoid the mistakes:

Sure! Here’s a complete SEO-rich blog post titled:


📝 Title: How to Use Cookie Storage with angular-auth-oidc-client in Angular 20 for Secure Token Management


🔍 Meta Description:

Learn how to implement cookie-based storage with angular-auth-oidc-client in Angular 20 to enhance security and performance. Step-by-step tutorial with code examples.


🚀 Introduction

When working with OAuth2/OpenID Connect in Angular applications, angular-auth-oidc-client is a popular and powerful library to manage authentication flows. By default, this library uses localStorage or sessionStorage to store tokens. However, for enhanced security and cross-tab persistence, cookie-based storage is often a better choice.

In this blog post, we’ll walk through how to use cookie storage in Angular 20 with angular-auth-oidc-client, and why it’s a smart move for modern, secure web apps.


💡 Why Use Cookie Storage Instead of localStorage?

FeaturelocalStorage/SessionStorageCookie Storage
Client-side accessYesYes (JS cookies)
Auto-sent with requestsNoYes (if needed)
HttpOnly❌ Not possible✅ (server-side only)
Cross-tab support✔️✔️
PersistencePersistent until deletedConfigurable

Using cookies allows for:

  • More secure handling of access/refresh tokens.
  • Better control in shared hosting or SSR environments.
  • Enhanced interoperability across browser tabs.

🧰 Prerequisites

  • Angular 20 project
  • angular-auth-oidc-client installed
npm install angular-auth-oidc-client

🛠️ Step 1: Create a Cookie Storage Service

Create a custom service to implement the Storage interface using cookies.

cookie-storage.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class CookieStorage implements Storage {
  get length(): number {
    return document.cookie.split(';').length;
  }

  clear(): void {
    document.cookie.split(';').forEach(cookie => {
      const name = cookie.split('=')[0].trim();
      document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/`;
    });
  }

  getItem(key: string): string | null {
    const name = `${key}=`;
    const decoded = decodeURIComponent(document.cookie);
    const cookies = decoded.split(';');
    for (const cookie of cookies) {
      const c = cookie.trim();
      if (c.indexOf(name) === 0) return c.substring(name.length);
    }
    return null;
  }

  key(index: number): string | null {
    const cookies = document.cookie.split(';');
    if (index >= 0 && index < cookies.length) {
      return cookies[index].split('=')[0].trim();
    }
    return null;
  }

  removeItem(key: string): void {
    document.cookie = `${key}=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/`;
  }

  setItem(key: string, value: string): void {
    document.cookie = `${key}=${value};path=/`;
  }
}

🛠️ Step 2: Configure the Auth Module with Cookie Storage

In your app.config.ts or wherever you bootstrap the application:

import { ApplicationConfig, importProvidersFrom } from '@angular/core';
import { AuthModule, LogLevel } from 'angular-auth-oidc-client';
import { CookieStorage } from './cookie-storage.service';

export const appConfig: ApplicationConfig = {
  providers: [
    importProvidersFrom(
      AuthModule.forRoot({
        config: {
          authority: 'https://your-auth-server.com',
          redirectUrl: window.location.origin,
          postLogoutRedirectUri: window.location.origin,
          clientId: 'your-client-id',
          scope: 'openid profile email',
          responseType: 'code',
          useRefreshToken: true,
          logLevel: LogLevel.Debug,
          storage: new CookieStorage(), // 👈 Use the custom storage
        },
      })
    ),
  ],
};

📋 Example Use in Component

In your component:

import { OidcSecurityService } from 'angular-auth-oidc-client';

export class AppComponent {
  constructor(public oidcSecurityService: OidcSecurityService) {}

  login() {
    this.oidcSecurityService.authorize();
  }

  logout() {
    this.oidcSecurityService.logoff();
  }
}

✅ Pros of This Approach

  • Cross-tab token access.
  • More control over token expiration.
  • Secure storage on client-side.
  • No more exposure in localStorage.

⚠️ Considerations

  • These are JavaScript-accessible cookies — they’re not HttpOnly, which are more secure but must be set by the server.
  • Make sure to configure path=/ to ensure global availability across routes.
  • For full security in production, consider using secure cookies via a backend proxy.

🏁 Conclusion

By integrating cookie-based storage in angular-auth-oidc-client, you give your Angular 20 app a more robust and secure authentication layer. It’s a future-forward technique for managing identity tokens—especially in progressive web apps and mobile-first Angular applications.


Ajay

Thanks

By therichpost

Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 19, MedusaJs, Next.js, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.