{"library":"simple-oauth2","title":"Simple OAuth2 Node.js Client","description":"Simple OAuth2 is a robust Node.js client library that provides a straightforward interface for interacting with OAuth 2.0 authorization servers. It supports various standard grant types including Authorization Code, Resource Owner Password Credentials, and Client Credentials, making it adaptable for diverse application architectures from web services to CLI tools. The package is currently stable at version 5.1.0, which mandates Node.js 14.x or higher, with a development branch (6.x) targeting Node.js 16.x and above. While a strict release cadence is not published, active development and maintenance are evident. Its primary differentiator lies in simplifying complex OAuth2 flows into an easy-to-use, promise-based API specifically for Node.js environments.","language":"javascript","status":"active","last_verified":"Thu Apr 23","install":{"commands":["npm install simple-oauth2"],"cli":null},"imports":["import { AuthorizationCode, ClientCredentials, ResourceOwnerPassword } from 'simple-oauth2';","const client = new AuthorizationCode(config);","const accessToken = await client.getToken(tokenParams);"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"import { AuthorizationCode } from 'simple-oauth2';\nimport express from 'express';\nimport 'dotenv/config'; // For process.env\n\nconst app = express();\nconst port = process.env.PORT || 3000;\n\n// Basic configuration for the OAuth2 client\nconst config = {\n  client: {\n    id: process.env.OAUTH_CLIENT_ID ?? 'YOUR_CLIENT_ID',\n    secret: process.env.OAUTH_CLIENT_SECRET ?? 'YOUR_CLIENT_SECRET'\n  },\n  auth: {\n    tokenHost: process.env.OAUTH_TOKEN_HOST ?? 'https://oauth.example.com',\n    authorizePath: process.env.OAUTH_AUTHORIZE_PATH ?? '/oauth/authorize',\n    tokenPath: process.env.OAUTH_TOKEN_PATH ?? '/oauth/token'\n  }\n};\n\nconst client = new AuthorizationCode(config);\nconst redirect_uri = process.env.OAUTH_REDIRECT_URI ?? `http://localhost:${port}/callback`;\nconst scope = process.env.OAUTH_SCOPE ?? 'read write';\n\n// Step 1: Redirect to the authorization server\napp.get('/auth', (req, res) => {\n  const authorizationUri = client.authorizeURL({\n    redirect_uri,\n    scope,\n    state: 'random_state_string' // Should be a securely generated random string\n  });\n  console.log(`Redirecting to: ${authorizationUri}`);\n  res.redirect(authorizationUri);\n});\n\n// Step 2: Handle the callback from the authorization server\napp.get('/callback', async (req, res) => {\n  const { code, state } = req.query;\n  \n  // You should validate the 'state' parameter here to prevent CSRF attacks\n  if (state !== 'random_state_string') {\n    return res.status(403).send('Invalid state parameter');\n  }\n\n  const tokenParams = {\n    code: code as string,\n    redirect_uri,\n    scope\n  };\n\n  try {\n    const accessToken = await client.getToken(tokenParams);\n    console.log('Successfully retrieved access token:');\n    console.log(accessToken.token);\n    \n    // Example: Refresh token if expired (or near expiration)\n    if (accessToken.expired()) {\n      console.log('Access token is expired, attempting to refresh...');\n      const refreshedToken = await accessToken.refresh();\n      console.log('Refreshed token:', refreshedToken.token);\n    }\n    \n    res.send(`Access Token: ${accessToken.token.access_token}<br/>Refresh Token: ${accessToken.token.refresh_token || 'N/A'}`);\n  } catch (error: any) {\n    console.error('Access Token Error', error.message);\n    res.status(500).send(`Authentication failed: ${error.message}`);\n  }\n});\n\napp.get('/', (req, res) => {\n  res.send('<a href=\"/auth\">Login with OAuth2</a>');\n});\n\napp.listen(port, () => {\n  console.log(`Server running at http://localhost:${port}`);\n  console.log('Visit /auth to initiate the OAuth2 flow.');\n});\n","lang":"typescript","description":"This quickstart demonstrates the Authorization Code grant type, covering redirecting a user for authorization, handling the callback, exchanging the authorization code for an access token, and refreshing an expired token. It uses environment variables for sensitive configuration and basic error handling.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}