@kingworks/web-sso-sdk
v1.0.0
Published
A pure functional SDK for SSO authentication with TSRPC support.
Readme
@kingworks/web-sso-sdk
A pure functional SDK for SSO authentication with TSRPC support.
Features
- Pure Function Library: No built-in request library, no hardcoded domains.
- Token Isolation: Store tokens in
localStoragescoped byapp_idandnamespace. - URL Handling:
- Generate login URL with
loginCallbackUrl. - Extract tokens from URL and clean up address bar.
- Generate login URL with
- Refresh Token Concurrency Control: Built-in Promise lock to prevent multiple simultaneous refresh calls.
Installation
npm install @kingworks/web-sso-sdkUsage
1. Initialization
import { SsoAuthClient } from '@kingworks/web-sso-sdk';
const authClient = new SsoAuthClient({
appId: 'your-app-id',
authServerUrl: 'https://auth-server.company.com/auth',
loginCallbackUrl: window.location.origin + '/login-receiver'
});2. Login
// Redirect to SSO login page
authClient.login();3. Handle Callback (in /login-receiver page)
// On the receiver page, handle the tokens and redirect back to original state
authClient.handleCallback();4. Seamless Token Refresh (TSRPC Flow)
In your apiClient.ts:
apiClient.flows.preApiReturnFlow.push(async v => {
if (v.return.err?.code === 'NOT_LOGIN' || v.return.err?.code === 'TOKEN_EXPIRED') {
// Attempt to refresh token
const newTokens = await authClient.doSeamlessRefresh(async (refreshToken, appId) => {
// Call your TSRPC refresh API here
const res = await apiClient.callApi('auth/RefreshToken', {
refreshToken,
appId
});
return res.isSucc ? res.res : null;
});
if (newTokens) {
// Retry the original request with new tokens
v.req.accessToken = newTokens.accessToken;
v.req.refreshToken = newTokens.refreshToken;
v.return = await apiClient.callApi(v.apiName as any, v.req);
return v;
} else {
// Refresh failed, go to login
authClient.login();
return null;
}
}
return v;
});5. Utilities
// Get current tokens
const tokens = authClient.getTokens();
// Clear tokens
authClient.clearTokens();
// Extract and clear tokens from URL (if not using a separate receiver page)
authClient.extractAndClearUrlTokens();License
ISC
