Skip to main content

Angular SDK

The Idenplane Angular SDK provides Angular-specific bindings for the idenplane-sdk, including an injectable AuthService, a route guard (AuthGuard), an HTTP interceptor (AuthInterceptor / authInterceptor), and an NgModule entry point (IdenplaneModule).

Installation​

npm install idenplane-angular idenplane-sdk rxjs

Quick Start​

1. Import IdenplaneModule.forRoot()​

// app.module.ts
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { IdenplaneModule } from 'idenplane-angular';

@NgModule({
imports: [
HttpClientModule,
IdenplaneModule.forRoot({
url: 'http://localhost:3000',
realm: 'my-realm',
clientId: 'my-app',
redirectUri: 'http://localhost:4200/callback',
// Your APIs that should receive the access token (exact origins).
bearerTokenOrigins: ['http://localhost:8080'],
}),
],
bootstrap: [AppComponent],
})
export class AppModule {}

2. Inject AuthService​

import { Component } from '@angular/core';
import { AuthService } from 'idenplane-angular';

@Component({
selector: 'app-nav',
template: `
<ng-container *ngIf="auth.isLoading$ | async; else content">
<span>Loading...</span>
</ng-container>
<ng-template #content>
<button *ngIf="!(auth.isAuthenticated$ | async)" (click)="auth.login()">
Sign In
</button>
<div *ngIf="auth.isAuthenticated$ | async">
<span>{{ (auth.user$ | async)?.name }}</span>
<button (click)="auth.logout()">Sign Out</button>
</div>
</ng-template>
`,
})
export class NavComponent {
constructor(public auth: AuthService) {}
}

3. Protect Routes with AuthGuard​

// app.routes.ts
import { Routes } from '@angular/router';
import { AuthGuard } from 'idenplane-angular';

export const routes: Routes = [
{ path: '', component: HomeComponent },
{
path: 'dashboard',
component: DashboardComponent,
canActivate: [AuthGuard],
},
{
path: 'admin',
component: AdminComponent,
canActivate: [AuthGuard],
data: { roles: ['admin'] },
},
];

4. Automatically Attach Bearer Tokens (HTTP Interceptor)​

The HTTP interceptor is registered automatically when you use IdenplaneModule.forRoot(). It attaches the access token only to the Idenplane server and to the origins in bearerTokenOrigins; see HTTP Interceptor.

For standalone / functional interceptor style (Angular 15+), provide the configuration with IDENPLANE_CONFIG:

// app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { authInterceptor, IDENPLANE_CONFIG } from 'idenplane-angular';

export const appConfig: ApplicationConfig = {
providers: [
{
provide: IDENPLANE_CONFIG,
useValue: {
url: 'http://localhost:3000',
realm: 'my-realm',
clientId: 'my-app',
redirectUri: 'http://localhost:4200/callback',
bearerTokenOrigins: ['http://localhost:8080'],
},
},
provideHttpClient(withInterceptors([authInterceptor])),
],
};

IdenplaneModule​

The IdenplaneModule.forRoot() method registers all providers including AuthService, AuthGuard, and AuthInterceptor.

Configuration​

OptionTypeRequiredDescription
urlstringYesIdenplane server URL
realmstringYesRealm name
clientIdstringYesOAuth2 client ID
redirectUristringYesRedirect URI after login
scopesstring[]NoOAuth2 scopes (default: ['openid', 'profile', 'email'])
storagestringNoStorage type: 'sessionStorage' | 'localStorage' | 'memory' (default: 'memory')
autoRefreshbooleanNoEnable automatic token refresh (default: true)
refreshBuffernumberNoSeconds before expiry to trigger refresh (default: 30)
bearerTokenOriginsstring[]NoOrigins, besides the Idenplane server, that the HTTP interceptor sends the access token to (default: none). Exact origins only: scheme, host and port. Since 2.0.0.

Module Configuration Example​

// app.module.ts
import { NgModule } from '@angular/core';
import { IdenplaneModule } from 'idenplane-angular';

@NgModule({
imports: [
IdenplaneModule.forRoot({
url: 'http://localhost:3000',
realm: 'my-realm',
clientId: 'my-app',
redirectUri: 'http://localhost:4200/callback',
scopes: ['openid', 'profile', 'email', 'custom:scope'],
storage: 'sessionStorage',
bearerTokenOrigins: ['https://api.example.com'],
autoRefresh: true,
refreshBuffer: 30,
}),
],
})
export class AppModule {}

AuthService​

The AuthService is an injectable service that provides reactive authentication state and methods.

Reactive Observables​

MemberTypeDescription
isAuthenticated$Observable<boolean>Reactive auth state
isLoading$Observable<boolean>True while initializing
user$Observable<UserInfo | null>Current user info

Synchronous Getters​

MemberTypeDescription
isAuthenticatedbooleanSynchronous auth state getter
userUserInfo | nullSynchronous user getter
getToken()string | nullCurrent access token

Methods​

MethodReturn TypeDescription
login(opts?)Promise<void>Redirect to login flow
logout()Promise<void>Log out and clear tokens
hasRole(role)booleanCheck if user has a realm role
hasPermission(perm)booleanCheck if user has a permission
getRoles()string[]Get all realm roles

AuthService Example with Async Pipe​

import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AuthService } from 'idenplane-angular';

@Component({
selector: 'app-user-profile',
standalone: true,
imports: [CommonModule],
template: `
<ng-container *ngIf="auth.isLoading$ | async">
<p>Loading...</p>
</ng-container>

<ng-container *ngIf="auth.isAuthenticated$ | async; else loggedOut">
<div class="profile">
<h2>{{ auth.user?.name }}</h2>
<p>{{ auth.user?.email }}</p>
<p>Roles: {{ auth.getRoles().join(', ') }}</p>

<button (click)="auth.logout()">Sign Out</button>
</div>
</ng-container>

<ng-template #loggedOut>
<div>
<p>You are not signed in.</p>
<button (click)="auth.login()">Sign In</button>
</div>
</ng-template>
`,
})
export class UserProfileComponent {
constructor(public auth: AuthService) {}
}

AuthService Example with Role Checking​

import { Component } from '@angular/core';
import { AuthService } from 'idenplane-angular';

@Component({
selector: 'app-admin-panel',
template: `
<div *ngIf="auth.hasRole('admin')">
<h2>Admin Panel</h2>
<p>Welcome, administrator!</p>
</div>

<div *ngIf="auth.hasPermission('read:reports')">
<h3>Reports</h3>
<button>View Reports</button>
</div>

<div *ngIf="!auth.hasRole('admin')">
<p>Access denied. You need admin privileges.</p>
</div>
`,
})
export class AdminPanelComponent {
constructor(public auth: AuthService) {}
}

Manual Token Access​

import { Component } from '@angular/core';
import { AuthService } from 'idenplane-angular';

@Component({
selector: 'app-token-display',
template: `
<div *ngIf="auth.isAuthenticated">
<p>Access Token:</p>
<code>{{ auth.getToken()?.substring(0, 20) }}...</code>
</div>
`,
})
export class TokenDisplayComponent {
constructor(public auth: AuthService) {}
}

AuthGuard​

The AuthGuard is a route guard implementing CanActivate that protects routes requiring authentication.

Usage with Roles​

// app.routes.ts
import { Routes } from '@angular/router';
import { AuthGuard } from 'idenplane-angular';

export const routes: Routes = [
{ path: '', component: HomeComponent },
{
path: 'dashboard',
component: DashboardComponent,
canActivate: [AuthGuard],
},
{
path: 'admin',
component: AdminComponent,
canActivate: [AuthGuard],
data: { roles: ['admin'] },
},
{
path: 'moderator',
component: ModeratorComponent,
canActivate: [AuthGuard],
data: { roles: ['moderator', 'content-editor'] },
},
];

AuthGuard Configuration​

The guard reads configuration from route.data:

Data KeyTypeDescription
rolesstring[]Required roles (user must have all)
loginPathstringRedirect path for unauthenticated users (default: /)
forbiddenPathstringRedirect path when authenticated but lacks roles

Custom Guard Configuration​

export const routes: Routes = [
{
path: 'admin',
component: AdminComponent,
canActivate: [AuthGuard],
data: {
roles: ['admin'],
loginPath: '/login',
forbiddenPath: '/access-denied',
},
},
];

HTTP Interceptor​

The HTTP interceptor attaches Authorization: Bearer <access token> to requests for trusted origins only:

  • the Idenplane server (the origin of url), and
  • the origins listed in bearerTokenOrigins.

Every other request goes out without the token, and a 401 from an untrusted origin does not trigger a token refresh. For a trusted origin, a 401 triggers one token refresh and one retry.

Origins are matched exactly, by scheme, host and port, never by prefix:

Request URLbearerTokenOrigins: ['https://api.example.com']
https://api.example.com/v1/orderstoken sent
https://api.example.com:443/v1/orderstoken sent (default port)
http://api.example.com/v1/ordersnot sent (different scheme)
https://api.example.com:8443/v1/ordersnot sent (different port)
https://sub.api.example.com/v1/ordersnot sent (different host)
https://api.example.com.evil.com/not sent (look-alike host)
/api/orders (relative)sent only if the app's own origin is listed

Each entry must be a bare origin, like https://api.example.com: no path, query, credentials or * wildcard. An invalid entry throws when AuthService is created, so a typo fails at startup.

Calling your own API​

Relative URLs such as /api/orders resolve to the origin the app is served from. To send the token to a same-origin API, list the app's own origin; for a separate API, list its origin. Write the origins out (or take them from your environment config) rather than reading window.location, which does not exist during server-side rendering:

IdenplaneModule.forRoot({
url: 'https://auth.example.com',
realm: 'my-realm',
clientId: 'my-app',
redirectUri: 'https://app.example.com/callback',
bearerTokenOrigins: [
'https://api.example.com', // a separate API
'https://app.example.com', // the app's own origin, for same-origin /api/... calls
],
});
Upgrading from idenplane-angular 1.x

Before 2.0.0 the interceptor sent the access token to every URL the app requested, third-party hosts included. From 2.0.0 it sends it only to the Idenplane server unless you list more origins. If your app calls its own API on any other origin, add that origin to bearerTokenOrigins, or those requests go out without a token and get 401.

Class-based Interceptor (NgModule style)​

The interceptor is registered automatically with IdenplaneModule.forRoot(); do not register it a second time.

If you provide AuthService and IDENPLANE_CONFIG yourself instead of using forRoot(), register it manually:

// app.module.ts
import { NgModule } from '@angular/core';
import { AuthInterceptor, AuthService, IDENPLANE_CONFIG } from 'idenplane-angular';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';

@NgModule({
imports: [HttpClientModule],
providers: [
{
provide: IDENPLANE_CONFIG,
useValue: {
url: 'http://localhost:3000',
realm: 'my-realm',
clientId: 'my-app',
redirectUri: 'http://localhost:4200/callback',
bearerTokenOrigins: ['http://localhost:8080'],
},
},
AuthService,
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true,
},
],
})
export class AppModule {}

Functional Interceptor (Standalone style)​

Same origin rules; provide the configuration with IDENPLANE_CONFIG as shown in the Quick Start.

Custom clients​

shouldAttachToken(url, origins), resolveBearerTokenOrigins(config) and normalizeOrigin(origin) are exported, so a fetch wrapper or WebSocket client can apply the same rule. AuthService.bearerTokenOrigins holds the resolved set.

Example: Making Authenticated Requests​

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { AuthService } from 'idenplane-angular';
import { catchError, of } from 'rxjs';

@Component({
selector: 'app-data-fetch',
template: `
<div *ngIf="data">
<h3>Protected Data</h3>
<pre>{{ data | json }}</pre>
</div>
<div *ngIf="error">
<p>Error: {{ error }}</p>
</div>
`,
})
export class DataFetchComponent implements OnInit {
data: any = null;
error: string | null = null;

constructor(
private http: HttpClient,
private auth: AuthService,
) {}

ngOnInit(): void {
// The interceptor attaches the token because the app's own origin
// is listed in bearerTokenOrigins (see "Calling your own API").
this.http.get('/api/protected-data')
.pipe(
catchError((err) => {
this.error = err.message;
return of(null);
}),
)
.subscribe((data) => {
this.data = data;
});
}
}

UserInfo Interface​

The UserInfo object contains the authenticated user's information:

interface UserInfo {
sub: string; // User ID
name?: string; // Display name
email?: string; // Email address
emailVerified?: boolean; // Email verification status
picture?: string; // Avatar URL
roles?: string[]; // Assigned roles
permissions?: string[]; // Direct permissions
[key: string]: any; // Any custom claims
}

Accessing User Info​

import { Component } from '@angular/core';
import { AuthService } from 'idenplane-angular';

@Component({
selector: 'app-user-card',
template: `
<div class="user-card">
<img
*ngIf="auth.user?.picture"
[src]="auth.user?.picture"
alt="Profile picture"
/>
<h2>{{ auth.user?.name || 'User' }}</h2>
<p>{{ auth.user?.email }}</p>
<span *ngIf="auth.user?.emailVerified">Email verified</span>
<span *ngIf="!auth.user?.emailVerified">Email not verified</span>
</div>
`,
})
export class UserCardComponent {
constructor(public auth: AuthService) {}
}

TypeScript Support​

The SDK is written in TypeScript and provides full type definitions:

import { AuthService, IdenplaneModule, AuthGuard, authInterceptor } from 'idenplane-angular';
import type { IdenplaneConfig, UserInfo, TokenResponse } from 'idenplane-sdk';

// AuthService is fully typed
constructor(public auth: AuthService) {
// auth.isAuthenticated$: Observable<boolean>
// auth.isLoading$: Observable<boolean>
// auth.user$: Observable<UserInfo | null>
// auth.isAuthenticated: boolean
// auth.user: UserInfo | null
}

Next Steps​

Quickstart Set up Idenplane and create your first authenticated app

Configuration Learn about all configuration options

API Reference Complete REST API documentation

JavaScript SDK Core SDK for non-framework applications


idenplane.com · GitHub · Discord