Skip to content

Authorization Code Flow ​

The authorization code flow is the recommended OAuth 2.0 flow for web applications that need to act on behalf of a user. It uses PKCE (Proof Key for Code Exchange) for added security.

Flow Overview ​

Step 1: Generate PKCE Parameters ​

javascript
// Generate a random code verifier
const codeVerifier = crypto.randomUUID() + crypto.randomUUID();

// Create the code challenge (S256)
const encoder = new TextEncoder();
const data = encoder.encode(codeVerifier);
const digest = await crypto.subtle.digest('SHA-256', data);
const codeChallenge = btoa(String.fromCharCode(...new Uint8Array(digest)))
  .replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');

Step 2: Redirect to Authorization Endpoint ​

GET /oauth/auth?
  response_type=code&
  client_id=YOUR_CLIENT_ID&
  redirect_uri=https://yourapp.com/callback&
  scope=openid profile projects:read&
  code_challenge=CODE_CHALLENGE&
  code_challenge_method=S256&
  state=RANDOM_STATE
ParameterRequiredDescription
response_typeYesMust be code
client_idYesYour OAuth client ID
redirect_uriYesMust match a registered redirect URI
scopeYesSpace-separated list of scopes
code_challengeYesPKCE challenge (S256)
code_challenge_methodYesMust be S256
stateRecommendedRandom string to prevent CSRF

Step 3: Exchange Code for Tokens ​

After the user approves, they're redirected to your redirect_uri with a code parameter:

bash
curl -X POST /oauth/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=authorization_code" \
  -d "code=AUTH_CODE" \
  -d "redirect_uri=https://yourapp.com/callback" \
  -d "client_id=YOUR_CLIENT_ID" \
  -d "client_secret=YOUR_CLIENT_SECRET" \
  -d "code_verifier=YOUR_CODE_VERIFIER"

Response:

json
{
  "access_token": "eyJhbG...",
  "token_type": "Bearer",
  "expires_in": 900,
  "refresh_token": "ey...",
  "scope": "openid profile projects:read"
}

Step 4: Use the Access Token ​

bash
curl -H "Authorization: Bearer ACCESS_TOKEN" \
  https://developers.knowify.com/api/projects

Refreshing Tokens ​

When the access token expires, use the refresh token:

bash
curl -X POST /oauth/token \
  -d "grant_type=refresh_token" \
  -d "refresh_token=REFRESH_TOKEN" \
  -d "client_id=YOUR_CLIENT_ID" \
  -d "client_secret=YOUR_CLIENT_SECRET"