Node.js client for OAuth2
—
The Authorization Code Grant is used for web applications where the client can securely store credentials and the user authorizes the application through a browser redirect. This is the most common OAuth 2.0 flow for web applications.
This grant type implements the OAuth 2.0 Authorization Code flow, which involves:
const { AuthorizationCode } = require('simple-oauth2');constructor(options: OAuth2Config): AuthorizationCodeCreates a new AuthorizationCode instance with OAuth 2.0 configuration validation.
Parameters:
options - OAuth 2.0 configuration object (see main documentation)Example:
const client = new AuthorizationCode({
client: {
id: 'your-client-id',
secret: 'your-client-secret'
},
auth: {
tokenHost: 'https://oauth-provider.com',
authorizePath: '/oauth/authorize',
tokenPath: '/oauth/token'
}
});authorizeURL(params: AuthorizeParams): stringCreates the authorization URL for redirecting users to the authorization server.
Parameters:
params.redirectURI (string) - Registered application URI where user is redirected after authenticationparams.scope (string | string[], optional) - Application privileges requestedparams.state (string, optional) - Opaque value to maintain state between request and callbackReturns: Complete authorization URL as string
Example:
const authorizationUri = client.authorizeURL({
redirectURI: 'http://localhost:3000/callback',
scope: ['read', 'write'],
state: 'random-state-string'
});
// Redirect user to authorizationUri
console.log('Redirect to:', authorizationUri);getToken(params: TokenParams, httpOptions?: any): Promise<AccessToken>Exchanges the authorization code for an access token.
Parameters:
params.code (string) - Authorization code received from callbackparams.redirectURI (string) - Same redirect URI used in authorization requestparams.scope (string | string[], optional) - Subset of original scopes to requesthttpOptions (object, optional) - HTTP options passed to underlying request libraryReturns: Promise resolving to AccessToken instance
Example:
// Handle callback (e.g., in Express route)
app.get('/callback', async (req, res) => {
const { code, state } = req.query;
const tokenParams = {
code: code,
redirectURI: 'http://localhost:3000/callback'
};
try {
const accessToken = await client.getToken(tokenParams);
console.log('Access token:', accessToken.token);
// Store token for future use
req.session.token = accessToken.token;
res.redirect('/dashboard');
} catch (error) {
console.error('Access Token Error', error.message);
res.status(500).json('Authentication failed');
}
});createToken(token: any): AccessTokenCreates an AccessToken instance from a plain token object (e.g., from storage).
Parameters:
token - Plain object representing an access token conforming to RFC 6750Returns: AccessToken instance with full token management capabilities
Example:
// Restore token from storage
const storedToken = JSON.parse(localStorage.getItem('oauth_token'));
const accessToken = client.createToken(storedToken);
// Check if token needs refresh
if (accessToken.expired()) {
const refreshedToken = await accessToken.refresh();
localStorage.setItem('oauth_token', JSON.stringify(refreshedToken.token));
}interface AuthorizeParams {
redirectURI: string;
scope?: string | string[];
state?: string;
[key: string]: any;
}
interface TokenParams {
code: string;
redirectURI: string;
scope?: string | string[];
[key: string]: any;
}const { AuthorizationCode } = require('simple-oauth2');
// 1. Configure client
const client = new AuthorizationCode({
client: {
id: process.env.CLIENT_ID,
secret: process.env.CLIENT_SECRET
},
auth: {
tokenHost: 'https://accounts.google.com',
authorizePath: '/o/oauth2/auth',
tokenPath: '/o/oauth2/token'
}
});
// 2. Redirect to authorization URL
const authorizationUri = client.authorizeURL({
redirectURI: 'http://localhost:3000/callback',
scope: 'profile email',
state: generateRandomState()
});
// 3. Handle callback and exchange code
const tokenParams = {
code: req.query.code,
redirectURI: 'http://localhost:3000/callback'
};
const accessToken = await client.getToken(tokenParams);
// 4. Use token for API calls
const userProfile = await fetch('https://api.example.com/profile', {
headers: {
'Authorization': `Bearer ${accessToken.token.access_token}`
}
});Install with Tessl CLI
npx tessl i tessl/npm-simple-oauth2