veslo-auth-sdk-ts-sandbox
v1.0.0
Published
TypeScript SDK for Veslo OIDC authentication
Downloads
8
Maintainers
Readme
Veslo Auth SDK TypeScript
TypeScript SDK for Veslo OIDC (OpenID Connect) authentication. This library provides a simple and type-safe way to integrate OAuth2/OIDC authentication flows into your TypeScript applications.
Installation
npm install veslo-auth-sdk-tsQuick Start
import { OAuth2Client } from "veslo-auth-sdk-ts";
// Initialize the OAuth2 client
const client = new OAuth2Client({
clientSecret: "your-client-secret",
clientId: "your-client-id",
redirectUri: "http://localhost:3000/callback",
});
// Generate authorization URL
const authUrl = client.generateAuthUrl({});
console.log(authUrl);
// After user authorizes, exchange the code for tokens
const code = "authorization-code-from-callback";
(async () => {
const { access_token } = await client.getToken(code);
console.log(access_token);
// Get user information
const userInfo = await client.getUserInfo(access_token);
console.log(userInfo);
})();API Reference
OAuth2Client
The main class for handling OAuth2/OIDC authentication flows.
Constructor
new OAuth2Client(config: OAuth2ClientConfig)Parameters:
config.clientId(string, required): Your OAuth2 client IDconfig.clientSecret(string, required): Your OAuth2 client secretconfig.redirectUri(string, required): The redirect URI registered with your OAuth2 provider
Example:
const client = new OAuth2Client({
clientId: "oidcCLIENT",
clientSecret: "wswsws",
redirectUri: "http://localhost:3000/callback",
});Methods
generateAuthUrl(options?)
Generates the authorization URL that users will be redirected to for authentication.
Parameters:
options.access_type(optional):"online"or"offline". Default:"offline". Use"offline"to receive a refresh token.options.scope(optional): String or array of strings representing the OAuth2 scopes. Default:"openid profile email".options.state(optional): A state parameter for CSRF protection.options.prompt(optional): Prompt parameter (e.g.,"consent","none").
Returns: string - The authorization URL
Example:
// Basic usage
const authUrl = client.generateAuthUrl({});
console.log(authUrl);
// With custom options
const authUrl = client.generateAuthUrl({
access_type: "offline",
scope: ["openid", "profile", "email"],
state: "random-state-string",
prompt: "consent",
});getToken(code)
Exchanges an authorization code for access and refresh tokens.
Parameters:
code(string, required): The authorization code received from the OAuth2 provider after user authorization.
Returns: Promise<TokenResponse> - An object containing:
access_token(string): The access tokenrefresh_token(string, optional): The refresh token (ifaccess_type: "offline"was used)expires_in(number, optional): Token expiration time in secondstoken_type(string, optional): Usually"Bearer"id_token(string, optional): OpenID Connect ID token
Example:
const code = "Niq0j2C57UDdKe8FGiYwpFYMbaRQCI2jkgFqO5P68sm";
const tokenResponse = await client.getToken(code);
console.log(tokenResponse.access_token);
console.log(tokenResponse.refresh_token);getUserInfo(accessToken)
Retrieves user information using an access token.
Parameters:
accessToken(string, required): The access token obtained fromgetToken().
Returns: Promise<UserInfo> - An object containing user information:
sub(string, optional): Subject identifieremail(string, optional): User's email addressname(string, optional): User's name- Additional fields may be present depending on the OAuth2 provider
Example:
const userInfo = await client.getUserInfo(access_token);
console.log(userInfo.email);
console.log(userInfo.name);refreshToken(refreshToken)
Refreshes an access token using a refresh token.
Parameters:
refreshToken(string, required): The refresh token obtained fromgetToken().
Returns: Promise<TokenResponse> - A new token response with updated tokens.
Example:
const newTokenResponse = await client.refreshToken(refresh_token);
console.log(newTokenResponse.access_token);Complete OAuth2 Flow Example
Here's a complete example of the OAuth2 authorization code flow:
import { OAuth2Client } from "veslo-auth-sdk-ts";
// 1. Initialize the client
const client = new OAuth2Client({
clientId: "oidcCLIENT",
clientSecret: "wswsws",
redirectUri: "http://localhost:3000/callback",
});
// 2. Generate authorization URL and redirect user
const authUrl = client.generateAuthUrl({
access_type: "offline", // Get refresh token
scope: ["openid", "profile", "email"],
state: "random-state-for-csrf-protection",
});
console.log("Redirect user to:", authUrl);
// 3. After user authorizes, handle the callback
// In your callback route handler:
app.get("/callback", async (req, res) => {
const { code, state } = req.query;
try {
// 4. Exchange code for tokens
const { access_token, refresh_token } = await client.getToken(
code as string
);
// 5. Get user information
const userInfo = await client.getUserInfo(access_token);
console.log("User authenticated:", userInfo);
// Store tokens securely (e.g., in session, database, etc.)
res.send("Authentication successful!");
} catch (error) {
console.error("Authentication failed:", error);
res.status(500).send("Authentication failed");
}
});
// 6. Later, refresh the token if needed
async function refreshAccessToken(refreshToken: string) {
try {
const tokenResponse = await client.refreshToken(refreshToken);
return tokenResponse.access_token;
} catch (error) {
console.error("Token refresh failed:", error);
throw error;
}
}Type Definitions
OAuth2ClientConfig
interface OAuth2ClientConfig {
clientId: string;
clientSecret: string;
redirectUri: string;
}TokenResponse
interface TokenResponse {
access_token: string;
refresh_token?: string;
expires_in?: number;
token_type?: string;
id_token?: string;
}UserInfo
interface UserInfo {
sub?: string;
email?: string;
name?: string;
[key: string]: any;
}Error Handling
All methods throw errors when API calls fail. Always wrap calls in try-catch blocks:
try {
const tokenResponse = await client.getToken(code);
const userInfo = await client.getUserInfo(tokenResponse.access_token);
} catch (error) {
console.error("Authentication error:", error.message);
// Handle error appropriately
}Requirements
- Node.js >= 18.0.0 (for native fetch API support)
- TypeScript >= 5.0.0
License
ISC
