Skip to content

Docs: Auth

ng-druid edited this page Aug 8, 2025 · 1 revision

Documentation for Angular Auth Library


Table of Contents

  1. Introduction
  2. Installation
  3. Overview
  4. Key Concepts
    • State Management
    • Authentication Workflow
    • Cookie Management
    • HTTP Interceptors
    • Callback Component
  5. Core Components
    • AuthModule
    • Components (AuthCallbackComponent)
  6. Key Services
    • AuthFacade
  7. Usage
    • Authentication Workflow
    • Accessing State Management
    • Utilizing HTTP Interceptors
  8. API Reference
  9. Examples
  10. Testing

1. Introduction

The Angular Auth Library provides an authentication framework designed to integrate OpenID Connect workflows with Angular applications. Using NgRx for centralized state management, it offers a streamlined approach to handling login, logout, session data, and user information. The library supports advanced features like effects-driven workflows, cookie-based session management, and interceptors for handling unauthorized access scenarios.


2. Installation

Install the library and its dependencies using npm:

npm install oidc-client ngrx

3. Overview

The library focuses on creating robust authentication workflows through state management and closely integrates with NgRx to handle asynchronous actions and user sessions efficiently.

Features:

  • State Management: Centralized store for managing user state and session data.
  • Authentication Workflow: Support for login, logout, and authentication callbacks using OpenID Connect.
  • Cookie Management: Manage and persist session data securely with the Cookie model.
  • HTTP Interceptors: Handles unauthorized requests (e.g., 401 status codes) seamlessly.
  • Facades: Simplifies interaction with the store and authentication workflows.

4. Key Concepts

4.1 State Management

The library uses NgRx to manage authentication-related data in a centralized store. It provides the following:

  • Reducers to process state updates based on dispatched actions.
  • Selectors for querying authentication state, such as accessing user details or session tokens.

4.2 Authentication Workflow

Authentication is handled using OpenID Connect via the oidc-client library:

  • Login Action: Initiates user login flow.
  • Logout Action: Signs the user out and clears session data.
  • Authentication Callback: Handles redirection back to the application post-login and processes tokens.

4.3 Cookie Management

Cookies are used to persist session data with configurable expiration policies for enhanced security.

4.4 HTTP Interceptors

The library includes an interceptor (LogoutInterceptor) that listens for 401 Unauthorized responses and handles application-level logout automatically.

4.5 Callback Component

The AuthCallbackComponent simplifies post-login workflows. It integrates with the facade to finalize authentication and redirects users to their intended destinations.


5. Core Components

5.1 AuthModule

The AuthModule encapsulates the library's functionality, including state management, metadata registration, and providing the AuthFacade.

Features:

  • Registers reducer and facade services.
  • Integrates AuthCallbackComponent.

Configuration Example:

import { AuthModule } from './auth.module';

@NgModule({
  imports: [
    AuthModule.forRoot(),
  ],
})
export class AppModule {}

5.2 Components

AuthCallbackComponent

This component handles authentication callbacks after OpenID Connect redirects. It finalizes user authentication and navigates the user to the appropriate application route.

Usage Example:

<classifieds-ui-auth-callback></classifieds-ui-auth-callback>

6. Key Services

6.1 AuthFacade

The AuthFacade provides a unified way to interact with authentication-related workflows. It abstracts the NgRx actions, selectors, and state management for ease of use.

Features:

  • Observables for accessing user data, authentication tokens, and session details.
  • Methods for login, logout, setting user data, and completing authentication.

API:

Method Description
login() Dispatches the Login action to initiate authentication flow.
logout() Signs the user out using the Logout action.
setUser(user: User) Updates the store with authenticated user data.
completeAuthentication() Finalizes authentication flow after a redirect.

Usage Example:

import { AuthFacade } from './lib/+state/auth.facade';

constructor(private authFacade: AuthFacade) {}

ngOnInit() {
  this.authFacade.getUser$.subscribe(user => console.log(user));
}

onLogin() {
  this.authFacade.login();
}

onLogout() {
  this.authFacade.logout();
}

7. Usage

7.1 Authentication Workflow

Simple login and logout workflows using the facade:

Component Usage:

import { AuthFacade } from './lib/+state/auth.facade';

constructor(private authFacade: AuthFacade) {}

onLogin() {
  this.authFacade.login();
}

onLogout() {
  this.authFacade.logout();
}

7.2 Accessing State Management

You can subscribe to state observables for accessing user data, tokens, and more.

Example:

authFacade.getUser$
  .subscribe(user => console.log('Authenticated user:', user));

authFacade.token$
  .subscribe(token => console.log('Authentication token:', token));

7.3 Utilizing HTTP Interceptors

Integrate LogoutInterceptor to handle unauthorized access:

App Module Configuration:

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { LogoutInterceptor } from './lib/http-interceptors/logout-interceptor';

@NgModule({
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: LogoutInterceptor, multi: true },
  ],
})
export class AppModule {}

8. API Reference

Classes

  1. AuthModule: Core module encapsulating library functionalities.
  2. AuthFacade: Centralized service for interacting with authentication workflows.
  3. AuthCallbackComponent: Handles OpenID Connect authentication redirects.

Models

  1. UserInfo: Represents basic user information like sub (identifier).
  2. PublicUserProfile: Represents publicly accessible user profile details.
  3. Cookie: Represents cookie data structure for managing session information.

9. Examples

Example 1: Integrate Callback Component

Use the AuthCallbackComponent for handling post-login redirects:

<classifieds-ui-auth-callback></classifieds-ui-auth-callback>

Example 2: Login and Logout Workflows

Handle login and logout workflows with facades:

import { AuthFacade } from './lib/+state/auth.facade';

constructor(private authFacade: AuthFacade) {}

onLogin() {
  this.authFacade.login();
}

onLogout() {
  this.authFacade.logout();
}

10. Testing

Unit tests included for facades, reducers, selectors, and components ensure functionality by validating outcomes against test cases.

Example Test for Reducer:

import { reducer, initialState } from './auth.reducer';
import { SetUser } from './auth.actions';

describe('Auth Reducer', () => {
  it('should update state with SetUser action', () => {
    const user = { sub: '12345' };
    const action = new SetUser(user);
    const state = reducer(initialState, action);

    expect(state.user).toEqual(user);
  });
});

To run tests, use:

npm run test

Conclusion

The Angular Auth Library simplifies authentication workflows by using NgRx-based state management, OpenID Connect, and facades. It is flexible, tested, and scalable, providing developers with a streamlined authentication solution for modern Angular applications.

Feel free to contribute or report issues to improve the library further!

Clone this wiki locally