Skip to main content
GET
/
v1
/
auth
/
oauth
/
authorize
/
initiate
{
  "token": "<string>",
  "url": "<string>"
}

Overview

Initiates the OAuth authorization process and returns a hosted UI URL where users authenticate. This is the first step in the OAuth 2.0 Authorization Code Flow with PKCE (Proof Key for Code Exchange). The redirect_uri provided must be whitelisted in your environment configuration. Authorization sessions expire after 10 minutes, so you must complete the flow before expiration.

When to Use

  • Starting an OAuth 2.0 authorization flow for third-party access
  • Implementing secure delegated authentication
  • Need users to grant permission to your application

PKCE Requirements

PKCE (Proof Key for Code Exchange) is mandatory for security. You must:
  1. Generate code_verifier: 43-128 random characters from [A-Za-z0-9-._~]
  2. Create code_challenge: BASE64URL(SHA256(code_verifier))
  3. Send code_challenge in this request
  4. Store code_verifier securely for use in Step 4 (token exchange)
import crypto from 'crypto';

function generateCodeVerifier() {
  return crypto.randomBytes(32).toString('base64url');
}

function generateCodeChallenge(verifier) {
  return crypto
    .createHash('sha256')
    .update(verifier)
    .digest('base64url');
}

const codeVerifier = generateCodeVerifier();
const codeChallenge = generateCodeChallenge(codeVerifier);

console.log('Store this:', codeVerifier);
console.log('Send this:', codeChallenge);

Flow Types

Hosted UI Flow (Default)

When not using mode=api, this endpoint redirects to a hosted UI where users authenticate:
  1. Call this endpoint to get hosted UI URL (302 redirect or JSON with URL)
  2. Redirect user to hosted UI for authentication
  3. User authenticates and grants permission automatically in UI
  4. User is redirected back to your redirect_uri with authorization code
  5. Exchange authorization code for tokens via POST /v1/auth/oauth/token

API Mode Flow

When using mode=api, you handle authentication in your application:
  1. Call this endpoint with mode=api to get JWT token
  2. Authenticate user via POST /v1/auth/login to get access token
  3. Call POST /v1/auth/oauth/authorize with both tokens to obtain authorization code
  4. Exchange authorization code for tokens via POST /v1/auth/oauth/token

Request

Query Parameters

client_id
string
required
Your public API client key (same as x-client-key header)Format: UUIDExample: 100a99cf-f4d3-4fa1-9be9-2e9828b20ebb
response_type
string
required
Must be code (authorization code flow only)Allowed values: code
redirect_uri
string
required
Your callback URL where user will be redirected after authorizationMust be whitelisted in environment settingsExample: https://yourapp.com/callback
state
string
required
CSRF protection token. Client-defined random string returned unchanged in callbackMinimum length: 8 charactersVerify this matches your original value when receiving the callbackExample: random_csrf_protection_string_12345
code_challenge
string
required
PKCE code challenge. BASE64URL(SHA256(code_verifier))Pattern: 43-128 characters from [A-Za-z0-9-._~]Example: M5iYUROLfJajkMMUkn3gpEquAVQpnK4m55NCeK40nls
code_challenge_method
string
required
PKCE challenge method. Must be S256 (SHA256 hashing)Allowed values: S256
client_secret
string
Client secret key - only required if secret key is issued for your environmentExample: 100a99cf-f4d3-4fa1-9be9-2e9828b20eaa
region
string
Set to us to route requests to the US backend environment (if available for your client)Allowed values: usDefault: international environment
mode
string
Set to api to return JSON instead of 302 redirect. Useful for API-only integrationsAllowed values: api

Headers

x-client-key
string
required
Your public API client key
x-secret-key
string
Your secret API key (required only if secret key is issued)

Response

token
string
JWT session token (valid for 10 minutes) - only returned when mode=apiFormat: JWTExample: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
url
string
Hosted UI URL where user should authenticateFormat: URIExample: https://app.example.com/account/login?token=eyJhbGc...

Success Responses

Returned when: mode=api parameter is provided
{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "url": "https://app.example.com/account/login?token=eyJhbGc..."
}

Error Responses

{
  "error": "invalid_request",
  "error_description": "PKCE is required. Missing code_challenge or code_challenge_method parameter"
}
Common causes:
  • Missing or invalid PKCE parameters
  • Invalid response_type (must be code)
  • Missing required parameters (client_id, redirect_uri, state)
  • Invalid parameter formats
{
  "message": "redirect_uri is not allowed"
}
Common causes:
  • redirect_uri not whitelisted in environment configuration
  • Invalid URL format
  • Parameter validation failures
{
  "error": "invalid_request",
  "error_description": "Too many authorization requests. Please try again later."
}
Cause: Rate limit exceeded. Wait before retrying.
{
  "message": "Invalid client key"
}
Cause: The x-client-key header contains an invalid or unknown key.
{
  "message": "Missing client key"
}
Cause: The required x-client-key header is missing.

Code Examples

curl -X GET "https://dev.api.baanx.com/v1/auth/oauth/authorize/initiate?client_id=100a99cf-f4d3-4fa1-9be9-2e9828b20ebb&response_type=code&redirect_uri=https://yourapp.com/callback&state=random_csrf_protection_string_12345&code_challenge=M5iYUROLfJajkMMUkn3gpEquAVQpnK4m55NCeK40nls&code_challenge_method=S256" \
  -H "x-client-key: 100a99cf-f4d3-4fa1-9be9-2e9828b20ebb"

Edge Cases and Important Notes

Session Expiration: Authorization sessions expire after 10 minutes. If your user doesn’t complete authentication within this window, you must restart the flow from Step 1.
Redirect URI Whitelist: The redirect_uri parameter MUST be whitelisted in your environment configuration. Contact your account manager to add URIs to the whitelist.
State Parameter Security: Always verify the state parameter returned in the callback matches the one you sent. This prevents CSRF attacks.

PKCE Code Verifier Storage

The code_verifier must be stored securely and retrieved during token exchange (Step 4):
  • Web apps: Use sessionStorage or secure session cookies
  • Mobile apps: Use secure device storage (Keychain on iOS, Keystore on Android)
  • Server-side apps: Store in secure session or database with expiration

Multiple Simultaneous Sessions

Each authorization session is independent. You can have multiple concurrent sessions with different state values, but each requires its own PKCE pair.

Rate Limiting

The endpoint implements rate limiting to prevent abuse. If you receive a 429 error, implement exponential backoff:
async function initiateWithRetry(maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await initiateOAuth();
    } catch (error) {
      if (error.status === 429 && i < maxRetries - 1) {
        await new Promise(resolve => setTimeout(resolve, 1000 * Math.pow(2, i)));
        continue;
      }
      throw error;
    }
  }
}

Next Steps

After initiating authorization:

Step 2: User Authentication

If using API mode, authenticate the user to get an access token

Step 3: Generate Authorization Code

Generate the authorization code using the JWT token

Step 4: Token Exchange

Exchange the authorization code for access and refresh tokens