The authorization_code flow is designed for browser-based applications and involves three steps: redirecting the user, handling the redirect back to the app, and exchanging the code for a token. You can use generateCodeVerifier() to enable PKCE (Proof Key for Code Exchange) for enhanced security.
import { OAuth2Client, generateCodeVerifier } from '@badgateway/oauth2-client';
const client = new OAuth2Client({
server: 'https://authserver.example/',
clientId: '...',
tokenEndpoint: '/token',
authorizationEndpoint: '/authorize',
});
// 1. Redirect the user to the authorization server
const codeVerifier = await generateCodeVerifier();
document.location = await client.authorizationCode.getAuthorizeUri({
redirectUri: 'https://my-app.example/',
state: 'some-string',
codeVerifier,
scope: ['scope1', 'scope2'],
});
// 2. Handle the redirect back to the app and obtain token
// (This part runs on the page the user is redirected to)
const oauth2Token = await client.authorizationCode.getTokenFromCodeRedirect(
document.location, // The current URL containing the 'code'
{
redirectUri: 'https://my-app.example/',
state: 'some-string', // Must match the state sent in step 1
codeVerifier, // Must match the verifier sent in step 1
}
);