CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-simple-oauth2

Node.js client for OAuth2

Pending
Overview
Eval results
Files

authorization-code.mddocs/

Authorization Code Grant

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.

Overview

This grant type implements the OAuth 2.0 Authorization Code flow, which involves:

  1. Redirecting users to the authorization server
  2. Receiving an authorization code via callback
  3. Exchanging the authorization code for an access token

Core Import

const { AuthorizationCode } = require('simple-oauth2');

Authorization Code Class

Constructor

constructor(options: OAuth2Config): AuthorizationCode

Creates 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'
  }
});

Generate Authorization URL

authorizeURL(params: AuthorizeParams): string

Creates the authorization URL for redirecting users to the authorization server.

Parameters:

  • params.redirectURI (string) - Registered application URI where user is redirected after authentication
  • params.scope (string | string[], optional) - Application privileges requested
  • params.state (string, optional) - Opaque value to maintain state between request and callback
  • Additional parameters are automatically serialized as query parameters

Returns: 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);

Exchange Code for Token

getToken(params: TokenParams, httpOptions?: any): Promise<AccessToken>

Exchanges the authorization code for an access token.

Parameters:

  • params.code (string) - Authorization code received from callback
  • params.redirectURI (string) - Same redirect URI used in authorization request
  • params.scope (string | string[], optional) - Subset of original scopes to request
  • Additional parameters are automatically serialized for the token request
  • httpOptions (object, optional) - HTTP options passed to underlying request library

Returns: 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');
  }
});

Create Token from Object

createToken(token: any): AccessToken

Creates an AccessToken instance from a plain token object (e.g., from storage).

Parameters:

  • token - Plain object representing an access token conforming to RFC 6750

Returns: 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));
}

Type Definitions

interface AuthorizeParams {
  redirectURI: string;
  scope?: string | string[];
  state?: string;
  [key: string]: any;
}

interface TokenParams {
  code: string;
  redirectURI: string;
  scope?: string | string[];
  [key: string]: any;
}

Common Usage Pattern

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

docs

access-token.md

authorization-code.md

client-credentials.md

index.md

resource-owner-password.md

tile.json