Ready-to-use examples

Quickstarts by language

The complete OAuth 2.1 flow with PKCE in PHP, Node.js, Python, in-browser JavaScript or cURL.

PHP 8.2+ (web application)

#

Complete example with no dependency: PHP sessions, secure randomness and cURL.

auth-orneos.php
<?php
declare(strict_types=1);
session_start();

$clientId     = 'orn_0123456789abcdef01234567';
$clientSecret = 'orns_confidential_secret';
$redirectUri  = 'https://example.com/auth-orneos.php';

// 1. Redirect to Orneos with PKCE
if (!isset($_GET['code'])) {
    $verifier  = rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '=');
    $challenge = rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '=');
    $state     = bin2hex(random_bytes(16));

    $_SESSION['orneos_oauth'] = ['verifier' => $verifier, 'state' => $state];

    $url = 'https://login.orneos.eu/oauth/authorize?' . http_build_query([
        'client_id'             => $clientId,
        'redirect_uri'          => $redirectUri,
        'response_type'         => 'code',
        'scope'                 => 'openid profile email',
        'state'                 => $state,
        'code_challenge'        => $challenge,
        'code_challenge_method' => 'S256',
    ]);
    header('Location: ' . $url);
    exit;
}

// 2. Check the state (anti-CSRF)
if (!hash_equals($_SESSION['orneos_oauth']['state'] ?? '', (string) ($_GET['state'] ?? ''))) {
    http_response_code(400);
    exit('Error: invalid state');
}

// 3. Exchange the code for tokens
$ch = curl_init('https://orneos.eu/oauth/token');
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_USERPWD        => $clientId . ':' . $clientSecret,
    CURLOPT_POSTFIELDS     => http_build_query([
        'grant_type'    => 'authorization_code',
        'code'          => (string) $_GET['code'],
        'redirect_uri'  => $redirectUri,
        'code_verifier' => $_SESSION['orneos_oauth']['verifier'],
    ]),
]);
$res = json_decode((string) curl_exec($ch), true);
curl_close($ch);
unset($_SESSION['orneos_oauth']);

if (empty($res['access_token'])) {
    exit('Error: ' . htmlspecialchars(json_encode($res)));
}

// 4. User profile
$ch = curl_init('https://orneos.eu/oauth/userinfo');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER     => ['Authorization: Bearer ' . $res['access_token']],
]);
$user = json_decode((string) curl_exec($ch), true);
curl_close($ch);

echo 'Welcome ' . htmlspecialchars($user['name']) . ' (' . htmlspecialchars($user['email']) . ')!';

Node.js 20+ (Express, native fetch)

#

The standard node:crypto module for PKCE and native fetch, without an OAuth library.

orneos-auth.mjs
import express from 'express';
import crypto from 'node:crypto';

const app = express();
const CLIENT_ID = 'orn_0123456789abcdef01234567';
const CLIENT_SECRET = 'orns_confidential_secret';
const REDIRECT_URI = 'http://localhost:3000/callback';

// In-memory storage, for the example
const pending = new Map();

app.get('/login', (req, res) => {
  const verifier = crypto.randomBytes(32).toString('base64url');
  const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
  const state = crypto.randomBytes(16).toString('hex');
  pending.set(state, { verifier });

  res.redirect('https://login.orneos.eu/oauth/authorize?' + new URLSearchParams({
    client_id: CLIENT_ID,
    redirect_uri: REDIRECT_URI,
    response_type: 'code',
    scope: 'openid profile email',
    state,
    code_challenge: challenge,
    code_challenge_method: 'S256',
  }));
});

app.get('/callback', async (req, res) => {
  const { code, state } = req.query;
  const saved = pending.get(state);
  if (!saved) return res.status(400).send('Unknown or expired state');
  pending.delete(state);

  const tokenRes = await fetch('https://orneos.eu/oauth/token', {
    method: 'POST',
    headers: {
      'Authorization': 'Basic ' + Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString('base64'),
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: new URLSearchParams({
      grant_type: 'authorization_code',
      code,
      redirect_uri: REDIRECT_URI,
      code_verifier: saved.verifier,
    }),
  });
  const tokens = await tokenRes.json();
  if (!tokens.access_token) return res.status(400).json(tokens);

  const userRes = await fetch('https://orneos.eu/oauth/userinfo', {
    headers: { 'Authorization': `Bearer ${tokens.access_token}` },
  });
  res.json({ user: await userRes.json() });
});

app.listen(3000, () => console.log('Ready on http://localhost:3000/login'));

Python 3.11+ (Requests)

#

PKCE with hashlib and secrets from the standard library, HTTP calls with requests. Plug it into your framework (FastAPI, Flask, Django…).

orneos_oauth.py
import base64, hashlib, secrets, requests
from urllib.parse import urlencode

CLIENT_ID = 'orn_0123456789abcdef01234567'
CLIENT_SECRET = 'orns_confidential_secret'
REDIRECT_URI = 'https://example.com/callback'

def generate_pkce_pair():
    verifier = secrets.token_urlsafe(32)
    digest = hashlib.sha256(verifier.encode('ascii')).digest()
    challenge = base64.urlsafe_b64encode(digest).rstrip(b'=').decode('ascii')
    return verifier, challenge

def authorization_url(challenge: str, state: str) -> str:
    return 'https://login.orneos.eu/oauth/authorize?' + urlencode({
        'client_id': CLIENT_ID,
        'redirect_uri': REDIRECT_URI,
        'response_type': 'code',
        'scope': 'openid profile email',
        'state': state,
        'code_challenge': challenge,
        'code_challenge_method': 'S256',
    })

def exchange_code(code: str, verifier: str) -> dict:
    r = requests.post(
        'https://orneos.eu/oauth/token',
        auth=(CLIENT_ID, CLIENT_SECRET),
        data={
            'grant_type': 'authorization_code',
            'code': code,
            'redirect_uri': REDIRECT_URI,
            'code_verifier': verifier,
        },
        timeout=10,
    )
    r.raise_for_status()
    return r.json()

def user_profile(access_token: str) -> dict:
    r = requests.get(
        'https://orneos.eu/oauth/userinfo',
        headers={'Authorization': f'Bearer {access_token}'},
        timeout=10,
    )
    r.raise_for_status()
    return r.json()

SPA and front-end (browser, no secret)

#

For a React, Vue or serverless JavaScript application, register a public client: no secret, the browser’s crypto API (crypto.subtle) computes the PKCE challenge. The /oauth/token, /oauth/userinfo and /oauth/revoke endpoints accept calls from any origin (CORS).

Keep tokens in memory rather than in localStorage.

auth-spa.js
const b64url = buf => btoa(String.fromCharCode(...new Uint8Array(buf)))
  .replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');

async function loginWithOrneos(clientId, redirectUri) {
  const verifier = b64url(crypto.getRandomValues(new Uint8Array(32)));
  const challenge = b64url(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier)));
  const state = b64url(crypto.getRandomValues(new Uint8Array(16)));

  sessionStorage.setItem('orneos_pkce_verifier', verifier);
  sessionStorage.setItem('orneos_oauth_state', state);

  window.location.assign('https://login.orneos.eu/oauth/authorize?' + new URLSearchParams({
    client_id: clientId,
    redirect_uri: redirectUri,
    response_type: 'code',
    scope: 'openid profile email',
    state,
    code_challenge: challenge,
    code_challenge_method: 'S256',
  }));
}

async function handleCallback(clientId, redirectUri) {
  const params = new URLSearchParams(window.location.search);
  const code = params.get('code');
  const verifier = sessionStorage.getItem('orneos_pkce_verifier');
  if (!code || !verifier || params.get('state') !== sessionStorage.getItem('orneos_oauth_state')) {
    throw new Error('Invalid state');
  }
  sessionStorage.removeItem('orneos_pkce_verifier');
  sessionStorage.removeItem('orneos_oauth_state');

  // Public client: client_id in the body, no secret
  const tokens = await (await fetch('https://orneos.eu/oauth/token', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
      grant_type: 'authorization_code',
      client_id: clientId,
      code,
      redirect_uri: redirectUri,
      code_verifier: verifier,
    }),
  })).json();

  const user = await (await fetch('https://orneos.eu/oauth/userinfo', {
    headers: { Authorization: `Bearer ${tokens.access_token}` },
  })).json();
  return { tokens, user };
}

cURL (testing in a terminal)

#

The whole flow from a terminal. Register http://localhost:8080/callback in the console: after consent, the browser shows a connection error, which is expected; copy the code from the address bar and exchange it within 60 seconds.

Terminal (bash)
# 1. Random code_verifier
VERIFIER=$(openssl rand -base64 32 | tr -d '=\n' | tr '+/' '-_')

# 2. S256 code_challenge
CHALLENGE=$(printf '%s' "$VERIFIER" | openssl dgst -sha256 -binary | openssl base64 -A | tr -d '=' | tr '+/' '-_')

# 3. Open this address in your browser
echo "https://login.orneos.eu/oauth/authorize?client_id=YOUR_CLIENT_ID&redirect_uri=http://localhost:8080/callback&response_type=code&scope=openid%20profile%20email&state=123&code_challenge=$CHALLENGE&code_challenge_method=S256"

# 4. Exchange the received code (public client: replace -u with -d "client_id=YOUR_CLIENT_ID")
curl -X POST https://orneos.eu/oauth/token \
  -u "YOUR_CLIENT_ID:YOUR_SECRET" \
  -d "grant_type=authorization_code" \
  -d "code=RECEIVED_CODE" \
  -d "redirect_uri=http://localhost:8080/callback" \
  -d "code_verifier=$VERIFIER"