@brandwacht/sso-auth
v0.0.19
Published
BWH SSO authentication library for Angular apps
Readme
@brandwacht/sso-auth
Drop-in SSO authentication library for Angular apps in the Brandwacht Huren B.V. ecosystem.
Provides the full login flow — SSO redirect, code exchange, JWT management — plus a ready-made login page with dark/light theme and EN/NL language switching.
Installation
npm install @brandwacht/sso-authLocal development (within the monorepo): The library is already wired via tsconfig paths. Build it with
npm run build— consuming apps resolve@brandwacht/sso-authfrom source automatically.
Quick start
1. Configure providers
// app.config.ts
import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { provideBwhSsoAuth, bwhJwtInterceptor } from '@brandwacht/sso-auth';
import { routes } from './app.routes';
import { environment } from '../environments/environment';
export const appConfig: ApplicationConfig = {
providers: [
provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(routes),
provideHttpClient(withInterceptors([bwhJwtInterceptor])),
provideBwhSsoAuth({
ssoAuthPortalUri: environment.ssoAuthPortalUri,
apiBaseUrl: environment.apiBaseUrl,
appBaseUrl: environment.appBaseUrl,
appId: 'my-app',
resolveLanding: (user) => '/dashboard',
}),
],
};2. Set up routes
// app.routes.ts
import { Routes } from '@angular/router';
import { BwhSsoLoginPage, ssoAuthGuard } from '@brandwacht/sso-auth';
export const routes: Routes = [
{ path: 'login', component: BwhSsoLoginPage },
{
path: '',
canActivate: [ssoAuthGuard],
children: [
{ path: 'dashboard', loadComponent: () => import('./dashboard/dashboard') },
{ path: '', redirectTo: 'dashboard', pathMatch: 'full' },
],
},
];That's it. You now have a fully working SSO login with JWT auth.
Multi-app SSO (single sign-on across multiple Angular apps)
This library supports automatic cross-app authentication. When a user logs in to any app, they are silently authenticated in all other apps that share the same SSO portal — no extra clicks needed.
How it works
Each app maintains its own JWT (stored in localStorage, scoped to its domain). Cross-app SSO works through the SSO portal's session:
App A (user logs in) SSO Portal App B (user visits later)
───────────────── ────────── ────────────────────────
1. Redirect to portal ──────────► 2. User authenticates
3. Portal creates session
◄────────── 4. Redirect back with code
5. Exchange code → JWT
(user is now logged
in to App A)
6. User opens App B
7. Guard → /login
8. Silent redirect ──────► 9. Session exists → return code
◄────── 10. Redirect back with code
11. Exchange code → JWT
(auto-logged in!)Steps 6–11 happen automatically with no user interaction. The BwhSsoLoginPage component detects that the user isn't authenticated and performs a silent SSO redirect (prompt=none) to the portal. If the portal has an active session, it returns a code immediately, and the app completes the login flow.
Setup checklist (repeat for each app)
Every app that participates in cross-app SSO needs all four of the following:
1. Same ssoAuthPortalUri
All apps must point to the same SSO portal so they share one session:
// App A
provideBwhSsoAuth({ ssoAuthPortalUri: 'https://oauth-portal.bwh.nl', ... })
// App B
provideBwhSsoAuth({ ssoAuthPortalUri: 'https://oauth-portal.bwh.nl', ... })
// App C
provideBwhSsoAuth({ ssoAuthPortalUri: 'https://oauth-portal.bwh.nl', ... })2. Unique appId and correct appBaseUrl per app
Each app has its own identity. The appBaseUrl must match the public URL exactly (including protocol and port) — the SSO portal uses it to validate redirect callbacks:
// App A
provideBwhSsoAuth({
appId: 'inventory',
appBaseUrl: 'https://inventory.bwh.nl',
...
})
// App B
provideBwhSsoAuth({
appId: 'crm',
appBaseUrl: 'https://crm.bwh.nl',
...
})Each
appIdmust be registered in the SSO portal and itsappBaseUrlmust be listed as an allowed redirect URI.
3. BwhSsoLoginPage on the login route
The login page component handles the silent SSO attempt. Without it, cross-app auto-login won't trigger:
// app.routes.ts — this route is REQUIRED
{ path: 'login', component: BwhSsoLoginPage }The route path must match the loginRoute config (defaults to '/login').
4. ssoAuthGuard on all protected routes
The guard redirects unauthenticated users to the login page, which then triggers silent SSO. It also preserves the original URL so users land on the page they intended to visit:
{
path: '',
canActivate: [ssoAuthGuard],
children: [
{ path: 'dashboard', ... },
{ path: 'settings', ... },
],
}5. bwhJwtInterceptor in provideHttpClient
Attaches the JWT to all outgoing HTTP requests:
provideHttpClient(withInterceptors([bwhJwtInterceptor]))Return URL preservation
When a user navigates to a deep link (e.g. https://crm.bwh.nl/clients/42) and isn't authenticated yet, the guard stores the intended URL. After silent SSO completes, the user lands on /clients/42 — not the default landing page. This works automatically.
Backend requirements for each app
Each app's backend must implement the SSO token exchange endpoint (see Backend contract). The backend validates the SSO tokens with the portal and returns an app-specific JWT.
Example: three-app setup
// === inventory/app.config.ts ===
provideBwhSsoAuth({
ssoAuthPortalUri: 'https://oauth-portal.bwh.nl',
apiBaseUrl: '/api',
appBaseUrl: 'https://inventory.bwh.nl',
appId: 'inventory',
resolveLanding: () => '/stock',
})
// === crm/app.config.ts ===
provideBwhSsoAuth({
ssoAuthPortalUri: 'https://oauth-portal.bwh.nl',
apiBaseUrl: '/api',
appBaseUrl: 'https://crm.bwh.nl',
appId: 'crm',
resolveLanding: () => '/clients',
})
// === admin/app.config.ts ===
provideBwhSsoAuth({
ssoAuthPortalUri: 'https://oauth-portal.bwh.nl',
apiBaseUrl: '/api',
appBaseUrl: 'https://admin.bwh.nl',
appId: 'admin',
resolveLanding: () => '/overview',
})Each app also needs the same route setup (login page + guard) shown in Quick start.
Configuration reference
provideBwhSsoAuth() accepts a BwhSsoAuthConfig object:
| Property | Type | Required | Default | Description |
|---|---|---|---|---|
| ssoAuthPortalUri | string | yes | — | URL of the BWH SSO portal (e.g. https://oauth-portal.bwh.nl) |
| apiBaseUrl | string | yes | — | Base URL for the app's API (e.g. /api) |
| appBaseUrl | string | yes | — | Public URL of this app, used for SSO redirect callback |
| appId | string | yes | — | Unique app identifier registered in the SSO portal |
| resolveLanding | (user: SsoAuthUser) => string \| Observable<string> | yes | — | Returns the URL to navigate to after login |
| storageKey | string | no | 'BWH_SSO_AUTH_STATE' | localStorage key for persisted auth state |
| loginRoute | string | no | '/login' | Route path for the login page |
| ssoCodeParam | string | no | 'sso_code' | Query parameter name for the SSO code |
| ssoEndpoint | string | no | '/auth/sso' | Backend endpoint path appended to apiBaseUrl |
Exports
Core auth
| Export | Description |
|---|---|
| SsoAuthService | Injectable service — user(), token(), isAuthenticated() signals, startSsoLogin(), ssoLogin(code), logout() |
| bwhJwtInterceptor | HTTP interceptor that attaches Authorization: Bearer <token> to all requests |
| ssoAuthGuard | Route guard — redirects unauthenticated users to the login page, preserves return URL |
| BwhSsoLoginPage | Standalone login page component with SSO button, silent auto-login, theme toggle, language switcher |
| provideBwhSsoAuth(config) | Provider helper — call once in app.config.ts |
I18n
| Export | Description |
|---|---|
| BwhI18nService | Lightweight i18n service (EN/NL). Use lang() signal, setLanguage(), t(key) |
| BwhTranslatePipe | Template pipe: {{ 'Hello' \| bwhT }} |
| registerTranslations(locale, map) | Extend the built-in translations with your own keys |
// Extend translations for your app
const i18n = inject(BwhI18nService);
i18n.registerTranslations('nl', {
Dashboard: 'Dashboard',
Settings: 'Instellingen',
});Theme
| Export | Description |
|---|---|
| BwhThemeService | Dark/light theme service. isDark$ observable, toggle(), setDark(boolean) |
SSO flow
User clicks "SSO Corporate Authentication"
│
▼
Browser redirects to SSO portal
{ssoAuthPortalUri}?redirectUri={appBaseUrl}{loginRoute}&appId={appId}
│
▼
User authenticates on SSO portal
│
▼
SSO portal redirects back to
{appBaseUrl}{loginRoute}?sso_code=<code>
│
▼
Library exchanges code for tokens (two-step):
1. POST {ssoAuthPortalUri}/api/sso/exchange { code } → SSO tokens
2. POST {apiBaseUrl}{ssoEndpoint} { authToken, refreshToken } → app JWT + user
│
▼
JWT + user stored in localStorage
│
▼
resolveLanding(user) called → navigate to resultBackend contract
The library expects the app's backend to expose a single endpoint:
POST {apiBaseUrl}/auth/sso
Content-Type: application/json
{
"authToken": "<access_token from SSO portal>",
"refreshToken": "<refresh_token from SSO portal>"
}
→ 200 OK
{
"token": "<app JWT>",
"user": {
"id": "...",
"email": "...",
"name": "...",
"role": "...",
"tenantId": "...",
...
}
}The endpoint path is configurable via ssoEndpoint.
Troubleshooting cross-app SSO
Silent login doesn't fire — user always sees the login button
- Missing
BwhSsoLoginPageon the login route. The silent SSO logic lives in this component'sngOnInit. Without it, nothing triggers the auto-login. - Missing
ssoAuthGuardon protected routes. If the guard isn't there, unauthenticated users stay on the page instead of being redirected to login. loginRoutemismatch. If you setloginRoute: '/auth/login'in config but the component is atpath: 'login', the redirects won't match.
Silent login redirects but comes back without logging in
- SSO portal doesn't support
prompt=none. The portal must handle this parameter: return a code if the user has an active session, or redirect back with?sso_error=...if not. - SSO portal session cookie is restricted. The portal's session cookie must be accessible when the browser navigates to the portal domain. Check that the cookie's
Domain,SameSite, andSecureattributes are correct. appIdnot registered in the portal. Each app'sappIdmust be registered, with itsappBaseUrlas an allowed redirect URI.
Code exchange fails (network error or 4xx)
- CORS not configured on the SSO portal. The library makes a
POSTto{ssoAuthPortalUri}/api/sso/exchangefrom the app's domain. The portal must allow cross-origin requests from all app domains. - Backend
/auth/ssoendpoint not implemented. Each app's backend must implement the token exchange endpoint (see Backend contract). apiBaseUrlis wrong. Verify it points to the correct backend. Open browser DevTools → Network tab and check for failed requests.
User lands on the wrong page after auto-login
The ssoAuthGuard preserves the original URL via a returnUrl query parameter. After authentication, the user is redirected to the page they originally requested. If this isn't working, make sure you're using ssoAuthGuard (not a custom guard) on your protected routes.
Build and publish
# Build the library
npm run build
# Publish to private registry
cd dist/sso-auth
npm publishRequirements
- Angular 21+
- RxJS 7.8+
- Tailwind CSS 4 (for the login page component's utility classes)
