UNPKG

signicat-client-ts

Version:

Community TypeScript client for Signicat Authentication REST API with automatic token management

413 lines (326 loc) β€’ 12 kB
# Signicat REST API TypeScript Client A community TypeScript client for the Signicat Authentication REST API with automatic token management. **πŸ“– [ν•œκ΅­μ–΄ λ¬Έμ„œ](./README-ko.md)** ## Installation ```bash npm install signicat-client-ts --save ``` ## Features - TypeScript interface for communicating with Signicat Authentication REST API - Axios-based HTTP client - Automatic access token management (issuance, caching, renewal) - TypeScript type definitions for type safety ## Quick Start ```typescript import { SignicatClient } from "signicat-client-ts"; // Configure automatic token management (static method) SignicatClient.configureAuth({ clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", // Optional parameters // tokenUrl: 'https://api.signicat.com/auth/open/connect/token', // default // scope: 'signicat-api', // default // expirationBuffer: 60 // refresh token 60 seconds before expiry (default) }); // Create client instance const client = new SignicatClient(); // API calls - tokens are automatically managed async function createSession() { try { const sessionRequest = { flow: "redirect", allowedProviders: ["nbid", "sbid"], requestedAttributes: ["firstName", "lastName", "email", "dateOfBirth"], language: "en", callbackUrls: { success: "https://example.com/success", abort: "https://example.com/abort", error: "https://example.com/error", }, }; const session = await client.authenticationSession.createSession(sessionRequest); console.log("Session created:", session); return session; } catch (error) { console.error("Error creating session:", error); throw error; } } ``` ## API Reference ### SignicatClient #### Automatic Token Management Configuration ```typescript // Configure automatic token management with static method SignicatClient.configureAuth({ clientId: string, // Signicat API client ID (required) clientSecret: string, // Signicat API client secret (required) tokenUrl: string, // Token endpoint URL (default: 'https://api.signicat.com/auth/open/connect/token') scope: string, // OAuth scope (default: 'signicat-api') expirationBuffer: number, // Token refresh time before expiry in seconds (default: 60) }); ``` #### Client Initialization Options ```typescript const client = new SignicatClient({ BASE: string, // API base URL (default: 'https://api.signicat.com/auth/rest') VERSION: string, // API version (default: '1') WITH_CREDENTIALS: boolean, // Include credentials (default: false) }); ``` ### AuthenticationSessionService #### createSession(requestBody: SessionRequestDto): Promise<SessionDataDto> Creates a new authentication session. **SessionRequestDto key properties:** - `flow`: Authentication flow type ("redirect" | "embedded" | "headless") - `requestedAttributes`: Array of user attributes to request (e.g., ["firstName", "lastName", "email"]) - `callbackUrls`: Callback URL configuration - `success`: Redirect URL on success - `abort`: Redirect URL on abort - `error`: Redirect URL on error - `allowedProviders`: Array of allowed authentication providers (e.g., ["nbid", "sbid", "idin"]) - `language`: UI language setting (ISO 639-1 format, e.g., "en", "no", "sv") - `sessionLifetime`: Session expiry time in seconds (default: 1200 seconds) - `externalReference`: External reference ID - `themeId`: Theme ID #### getSession(id: string, sessionNonce?: string): Promise<SessionDataDto> Retrieves the status of an existing session. #### cancelSession(id: string): Promise<SessionDataDto> Cancels an ongoing session. ## Error Handling The client returns API errors as `ApiError` instances. Handle errors as follows: ```typescript import { ApiError } from "signicat-client-ts"; try { const session = await client.authenticationSession.createSession(sessionData); // Handle success } catch (error) { if (error instanceof ApiError) { console.error("API Error:", error.status, error.message); // Handle error based on status code switch (error.status) { case 400: // Handle bad request break; case 401: // Handle authentication error break; case 403: // Handle authorization error break; case 404: // Handle resource not found break; case 500: // Handle server error break; default: // Handle other errors break; } } else { console.error("Unknown error:", error); } } ``` ## How Automatic Token Management Works The automatic token management feature works as follows: 1. Call `SignicatClient.configureAuth()` to set client ID and secret. 2. Access tokens are automatically retrieved on the first API request. 3. Tokens are cached in memory and reused for subsequent requests. 4. New tokens are automatically retrieved before expiry (default: 60 seconds before expiration). 5. If token-related errors (401) occur, tokens are automatically renewed and requests are retried. This approach allows users to use the API without worrying about token management. ## Framework Integration Guides ### Using with NestJS #### Module Setup ```typescript // signicat.module.ts import { Module } from "@nestjs/common"; import { SignicatClient } from "signicat-client-ts"; @Module({ providers: [ { provide: "SIGNICAT_CLIENT", useFactory: () => { // Configure automatic token management SignicatClient.configureAuth({ clientId: process.env.SIGNICAT_CLIENT_ID, clientSecret: process.env.SIGNICAT_CLIENT_SECRET, }); // Create client instance return new SignicatClient(); }, }, ], exports: ["SIGNICAT_CLIENT"], }) export class SignicatModule {} ``` #### Service Usage ```typescript // auth.service.ts import { Injectable, Inject } from "@nestjs/common"; import { SignicatClient, SessionRequestDto } from "signicat-client-ts"; @Injectable() export class AuthService { constructor(@Inject("SIGNICAT_CLIENT") private readonly signicatClient: SignicatClient) {} async createAuthenticationSession(sessionData: SessionRequestDto) { try { const session = await this.signicatClient.authenticationSession.createSession(sessionData); return session; } catch (error) { // Handle error throw error; } } async getSessionStatus(sessionId: string) { try { const sessionStatus = await this.signicatClient.authenticationSession.getSession(sessionId); return sessionStatus; } catch (error) { // Handle error throw error; } } async cancelSession(sessionId: string) { try { const result = await this.signicatClient.authenticationSession.cancelSession(sessionId); return result; } catch (error) { // Handle error throw error; } } } ``` ### Using with React In React applications, you can create a service class to communicate with the Signicat API. #### Creating API Service ```typescript // signicatService.ts import { SignicatClient, SessionRequestDto, SessionDataDto } from "signicat-client-ts"; // Warning: Client secrets should not be exposed in browser environments. // In React applications, it's recommended to manage tokens through a backend. class SignicatService { private client: SignicatClient; constructor() { // Do not use automatic token management directly in the client, // instead get tokens from your backend. // Use SignicatClient.configureAuth() on your backend. this.client = new SignicatClient(); } async createSession(sessionData: SessionRequestDto): Promise<SessionDataDto> { try { return await this.client.authenticationSession.createSession(sessionData); } catch (error) { console.error("Failed to create session:", error); throw error; } } async getSession(sessionId: string): Promise<SessionDataDto> { try { return await this.client.authenticationSession.getSession(sessionId); } catch (error) { console.error("Failed to get session:", error); throw error; } } async cancelSession(sessionId: string): Promise<SessionDataDto> { try { return await this.client.authenticationSession.cancelSession(sessionId); } catch (error) { console.error("Failed to cancel session:", error); throw error; } } } // Create singleton instance export const signicatService = new SignicatService(); ``` ## Supported Authentication Providers (allowedProviders) ### 🎯 Type-Safe Provider Selection The library provides TypeScript support for `allowedProviders` with compile-time validation and IDE auto-completion. #### Basic Usage with Type Safety ```typescript import { SignicatClient, SessionRequestDto, AuthenticationProvider } from "signicat-client-ts"; // βœ… Type-safe approach (recommended) const sessionRequest: SessionRequestDto = { flow: SessionRequestDto.flow.REDIRECT, allowedProviders: [ AuthenticationProvider.NBID, // Norwegian BankID AuthenticationProvider.SK_MOBILEID, // SK Mobile-ID AuthenticationProvider.MITID, // Danish MitID ], requestedAttributes: ["firstName", "lastName", "email"], // ... other options }; ``` #### Dynamic Provider Validation ```typescript import { isValidAuthenticationProvider } from "signicat-client-ts"; // Validate user input const userInput = ["nbid", "invalid-provider", "mitid"]; const validProviders = userInput.filter(isValidAuthenticationProvider); // Result: ["nbid", "mitid"] // Safe provider selection from user input function createSessionWithUserProviders(userProviders: string[]) { const validProviders = userProviders.filter(isValidAuthenticationProvider); if (validProviders.length === 0) { throw new Error("No valid providers specified"); } return { allowedProviders: validProviders, // ... other session options }; } ``` ### Supported Providers The following authentication providers are supported: - `ftn` - Finnish Trust Network - `nbid` - Norwegian BankID - `mojeid-pl` - MojeID (Poland) - `beid` - Belgium eID - `sk-mobileid` - SK Mobile-ID (Estonia & Lithuania) - `et-smartcard` - Estonian ID Card - `eparaksts-mobile` - eParaksts Mobile (Latvia) - `idin` - iDIN (Netherlands) - `mitid` - Danish MitID - `samleikin` - Samleikin (Iceland) - `spid` - Italian SPID - `itsme` - Itsme (Belgium) ### Benefits of Type-Safe Provider Selection βœ… **IDE Auto-completion**: Get intelligent suggestions while typing βœ… **Compile-time Validation**: Catch provider name typos before runtime βœ… **Type Safety**: Ensure only valid providers are used ### Example: Complete Type-Safe Session Creation ```typescript import { SignicatClient, SessionRequestDto, AuthenticationProvider } from "signicat-client-ts"; // Configure client SignicatClient.configureAuth({ clientId: process.env.SIGNICAT_CLIENT_ID!, clientSecret: process.env.SIGNICAT_CLIENT_SECRET!, }); const client = new SignicatClient(); // Create session with type-safe providers const session = await client.authenticationSession.createSession({ flow: SessionRequestDto.flow.REDIRECT, allowedProviders: [AuthenticationProvider.NBID, AuthenticationProvider.MITID, AuthenticationProvider.IDIN], requestedAttributes: ["firstName", "lastName", "email", "dateOfBirth"], callbackUrls: { success: "https://yourapp.com/auth/success", error: "https://yourapp.com/auth/error", abort: "https://yourapp.com/auth/abort", }, language: "en", sessionLifetime: 1200, }); ``` **Note**: The actual available providers may vary depending on your Signicat account configuration. For detailed information, please refer to the [Signicat Developer Documentation](https://developer.signicat.com/identity-methods/). ## Contributing Contributions are welcome! Please feel free to submit a Pull Request. ## License MIT ## Links - [Signicat Developer Documentation](https://developer.signicat.com/) - [ν•œκ΅­μ–΄ λ¬Έμ„œ](./README-ko.md)