Quick Start Guide

This guide shows you how to perform a basic OAuth 2.0 authorization code flow using PKCE.

1. Fetch Service Configuration

AppAuth can automatically discover endpoints from an OpenID Connect issuer URL.

import { AuthorizationServiceConfiguration } from '@openid/appauth';

const openIdConnectUrl = 'https://accounts.google.com';
let configuration: AuthorizationServiceConfiguration;

AuthorizationServiceConfiguration.fetchFromIssuer(openIdConnectUrl)
  .then(response => {
    console.log('Fetched service configuration', response);
    configuration = response;
  });

2. Initialize the Notifier and Handler

The AuthorizationNotifier is used to receive the result of the authorization request.

import { 
  AuthorizationNotifier, 
  RedirectRequestHandler, 
  AuthorizationRequest 
} from '@openid/appauth';

const notifier = new AuthorizationNotifier();
const authorizationHandler = new RedirectRequestHandler();

authorizationHandler.setAuthorizationNotifier(notifier);

// Set a listener to handle the response
notifier.setAuthorizationListener((request, response, error) => {
  if (response) {
    console.log('Authorization Code:', response.code);
    // Proceed to exchange code for token
  }
});

3. Make the Authorization Request

const request = new AuthorizationRequest({
    client_id: 'YOUR_CLIENT_ID',
    redirect_uri: 'YOUR_REDIRECT_URI',
    scope: 'openid profile email',
    response_type: AuthorizationRequest.RESPONSE_TYPE_CODE,
    state: undefined, // Will be automatically generated
    extras: {'prompt': 'consent', 'access_type': 'offline'}
  });

authorizationHandler.performAuthorizationRequest(configuration, request);

4. Exchange Code for Token

Once the listener receives the code, use the BaseTokenRequestHandler to get an Access Token.

import { BaseTokenRequestHandler, TokenRequest, GRANT_TYPE_AUTHORIZATION_CODE } from '@openid/appauth';

const tokenHandler = new BaseTokenRequestHandler();

const tokenRequest = new TokenRequest({
    client_id: 'YOUR_CLIENT_ID',
    redirect_uri: 'YOUR_REDIRECT_URI',
    grant_type: GRANT_TYPE_AUTHORIZATION_CODE,
    code: codeFromResponse,
    refresh_token: undefined,
    extras: { 'code_verifier': originalRequestInternalCodeVerifier }
  });

tokenHandler.performTokenRequest(configuration, tokenRequest)
  .then(response => {
    console.log('Access Token:', response.accessToken);
  });