Skip to Content
⚠️ Note: Some details in this documentation may not be fully accurate yet.
API ReferenceCore

API Reference - Core

Complete API documentation for @alien_org/sso-sdk-core.

AlienSsoClient

Main client class for Alien SSO authentication.

Constructor

new AlienSsoClient(config: AlienSsoClientConfig)

Parameters:

ParameterTypeRequiredDescription
ssoBaseUrlstringYesBase URL of the SSO service
providerAddressstringYesYour provider address
pollingIntervalnumberNoPolling interval in ms (default: 5000)

Example:

const client = new AlienSsoClient({ ssoBaseUrl: 'https://sso.alien-api.com', providerAddress: 'your-provider-address', pollingInterval: 5000 });

Authentication Methods

Initiates OAuth2 authorization flow with response_mode=json for SPAs.

async generateDeeplink(): Promise<AuthorizeResponse>

HTTP Request:

GET /oauth/authorize?response_type=code&response_mode=json&client_id={providerAddress}&scope=openid&code_challenge={challenge}&code_challenge_method=S256

Returns: AuthorizeResponse

{ deep_link: string; // Deep link for QR code or mobile redirect polling_code: string; // Code for polling authentication status expired_at: number; // Unix timestamp when session expires }

Side Effects:

  • Generates PKCE code verifier and challenge (S256)
  • Stores code verifier in sessionStorage

Example:

const { deep_link, polling_code, expired_at } = await client.generateDeeplink(); console.log('Deep link:', deep_link); console.log('Expires:', new Date(expired_at * 1000));

pollAuth()

Polls for authentication completion status.

async pollAuth(pollingCode: string): Promise<PollResponse>

HTTP Request:

POST /oauth/poll Content-Type: application/json Body: { "polling_code": "..." }

Parameters:

ParameterTypeDescription
pollingCodestringPolling code from generateDeeplink()

Returns: PollResponse

{ status: 'pending' | 'authorized' | 'rejected' | 'expired'; authorization_code?: string; // Only present when status is 'authorized' }

Status Values:

StatusDescription
pendingUser hasn’t completed authentication yet
authorizedUser approved, authorization_code available
rejectedUser denied authentication
expiredSession expired

exchangeToken()

Exchanges authorization code for tokens (OAuth2 token endpoint).

async exchangeToken(authorizationCode: string): Promise<TokenResponse>

HTTP Request:

POST /oauth/token Content-Type: application/x-www-form-urlencoded Body: grant_type=authorization_code&code={code}&client_id={providerAddress}&code_verifier={verifier}

Parameters:

ParameterTypeDescription
authorizationCodestringAuthorization code from pollAuth()

Returns: TokenResponse

{ access_token: string; // JWT access token id_token: string; // JWT ID token with user claims refresh_token: string; // Opaque refresh token token_type: string; // "Bearer" expires_in: number; // Token lifetime in seconds }

Side Effects:

  • Retrieves code verifier from sessionStorage
  • Stores all tokens in localStorage
  • Clears code verifier from sessionStorage

verifyAuth()

Verifies authentication by calling the userinfo endpoint. Automatically refreshes token on 401.

async verifyAuth(): Promise<UserInfoResponse | null>

HTTP Request:

GET /oauth/userinfo Authorization: Bearer {access_token}

Returns: UserInfoResponse | null

{ sub: string; // User identifier (session address) }

Returns null if not authenticated or token invalid.


refreshAccessToken()

Refreshes the access token using the stored refresh token.

async refreshAccessToken(): Promise<TokenResponse>

HTTP Request:

POST /oauth/token Content-Type: application/x-www-form-urlencoded Body: grant_type=refresh_token&refresh_token={token}&client_id={providerAddress}

Returns: TokenResponse (same as exchangeToken())

Side Effects:

  • Updates all tokens in localStorage
  • On failure, calls logout() to clear invalid tokens

Throws: Error if no refresh token available or refresh fails


withAutoRefresh()

Executes a function with automatic token refresh on 401 error.

async withAutoRefresh<T>( requestFn: () => Promise<T>, maxRetries?: number ): Promise<T>

Parameters:

ParameterTypeDefaultDescription
requestFnfunction-Async function to execute
maxRetriesnumber1Max retry attempts

Example:

const data = await client.withAutoRefresh(async () => { const res = await fetch('/api/data', { headers: { Authorization: `Bearer ${client.getAccessToken()}` } }); if (res.status === 401) { throw Object.assign(new Error('Unauthorized'), { response: { status: 401 } }); } return res.json(); });

logout()

Clears all stored authentication data.

logout(): void

Side Effects:

  • Removes access_token, id_token, refresh_token, token_expiry from localStorage
  • Removes code_verifier from sessionStorage

Token Methods

getAccessToken()

Retrieves stored access token.

getAccessToken(): string | null

getIdToken()

Retrieves stored ID token.

getIdToken(): string | null

getRefreshToken()

Retrieves stored refresh token.

getRefreshToken(): string | null

hasRefreshToken()

Checks if a refresh token is available.

hasRefreshToken(): boolean

getAuthData()

Decodes JWT token and returns claims. Does NOT verify signature.

getAuthData(): TokenInfo | null

Returns: TokenInfo | null

{ iss: string; // Issuer URL sub: string; // Subject (user identifier) aud: string | string[]; // Audience (your provider address) exp: number; // Expiration timestamp iat: number; // Issued at timestamp nonce?: string; // Nonce (if provided in authorize) auth_time?: number; // Authentication time }

Note: Returns null if token invalid, expired, or audience doesn’t match.


getSubject()

Gets the subject (user identifier) from the token.

getSubject(): string | null

Shorthand for getAuthData()?.sub.


isTokenExpired()

Checks if the current token is expired based on exp claim.

isTokenExpired(): boolean

isAccessTokenExpired()

Checks if the access token is expired or will expire within 5 minutes.

isAccessTokenExpired(): boolean

Uses stored expiry timestamp for efficiency.


Types

AlienSsoClientConfig

interface AlienSsoClientConfig { ssoBaseUrl: string; providerAddress: string; pollingInterval?: number; }

AuthorizeResponse

interface AuthorizeResponse { deep_link: string; polling_code: string; expired_at: number; }

PollResponse

interface PollResponse { status: 'pending' | 'authorized' | 'rejected' | 'expired'; authorization_code?: string; }

TokenResponse

interface TokenResponse { access_token: string; id_token: string; refresh_token: string; token_type: string; expires_in: number; }

UserInfoResponse

interface UserInfoResponse { sub: string; }

TokenInfo

interface TokenInfo { iss: string; sub: string; aud: string | string[]; exp: number; iat: number; nonce?: string; auth_time?: number; }

Storage Keys

localStorage

KeyDescription
alien-sso_access_tokenJWT access token
alien-sso_id_tokenJWT ID token
alien-sso_refresh_tokenRefresh token
alien-sso_token_expiryExpiry timestamp (ms)

sessionStorage

KeyDescription
alien-sso_code_verifierPKCE code verifier

HTTP Endpoints Summary

MethodEndpointDescription
GET/oauth/authorizeStart authorization flow
POST/oauth/pollPoll for authorization status
POST/oauth/tokenExchange code or refresh token
GET/oauth/userinfoGet user info
GET/oauth/jwksGet public keys for JWT verification
GET/.well-known/openid-configurationOIDC discovery document

Error Handling

All async methods can throw errors:

try { await client.generateDeeplink(); } catch (error) { // Network error, invalid provider, or server error } try { await client.exchangeToken(code); } catch (error) { // Invalid code, expired code, or PKCE mismatch } try { await client.refreshAccessToken(); } catch (error) { // Refresh token expired or revoked // Client automatically calls logout() }

Next Steps

Last updated on