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:
| Parameter | Type | Required | Description |
|---|---|---|---|
ssoBaseUrl | string | Yes | Base URL of the SSO service |
providerAddress | string | Yes | Your provider address |
pollingInterval | number | No | Polling interval in ms (default: 5000) |
Example:
const client = new AlienSsoClient({
ssoBaseUrl: 'https://sso.alien-api.com',
providerAddress: 'your-provider-address',
pollingInterval: 5000
});Authentication Methods
generateDeeplink()
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=S256Returns: 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:
| Parameter | Type | Description |
|---|---|---|
pollingCode | string | Polling code from generateDeeplink() |
Returns: PollResponse
{
status: 'pending' | 'authorized' | 'rejected' | 'expired';
authorization_code?: string; // Only present when status is 'authorized'
}Status Values:
| Status | Description |
|---|---|
pending | User hasn’t completed authentication yet |
authorized | User approved, authorization_code available |
rejected | User denied authentication |
expired | Session 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:
| Parameter | Type | Description |
|---|---|---|
authorizationCode | string | Authorization 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:
| Parameter | Type | Default | Description |
|---|---|---|---|
requestFn | function | - | Async function to execute |
maxRetries | number | 1 | Max 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(): voidSide Effects:
- Removes
access_token,id_token,refresh_token,token_expiryfromlocalStorage - Removes
code_verifierfromsessionStorage
Token Methods
getAccessToken()
Retrieves stored access token.
getAccessToken(): string | nullgetIdToken()
Retrieves stored ID token.
getIdToken(): string | nullgetRefreshToken()
Retrieves stored refresh token.
getRefreshToken(): string | nullhasRefreshToken()
Checks if a refresh token is available.
hasRefreshToken(): booleangetAuthData()
Decodes JWT token and returns claims. Does NOT verify signature.
getAuthData(): TokenInfo | nullReturns: 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 | nullShorthand for getAuthData()?.sub.
isTokenExpired()
Checks if the current token is expired based on exp claim.
isTokenExpired(): booleanisAccessTokenExpired()
Checks if the access token is expired or will expire within 5 minutes.
isAccessTokenExpired(): booleanUses 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
| Key | Description |
|---|---|
alien-sso_access_token | JWT access token |
alien-sso_id_token | JWT ID token |
alien-sso_refresh_token | Refresh token |
alien-sso_token_expiry | Expiry timestamp (ms) |
sessionStorage
| Key | Description |
|---|---|
alien-sso_code_verifier | PKCE code verifier |
HTTP Endpoints Summary
| Method | Endpoint | Description |
|---|---|---|
| GET | /oauth/authorize | Start authorization flow |
| POST | /oauth/poll | Poll for authorization status |
| POST | /oauth/token | Exchange code or refresh token |
| GET | /oauth/userinfo | Get user info |
| GET | /oauth/jwks | Get public keys for JWT verification |
| GET | /.well-known/openid-configuration | OIDC 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
- React API Reference - React SDK documentation
- Core Integration Guide - Integration guide
- Demo App - Example implementation