v1.0 · OAuth 2.0 + OpenID Connect

Secure Authentication
with OAuth2 & OIDC

Everything you need to integrate secure login, tokens, and user identity into your app — using standard OAuth 2.0 and OIDC protocols.

Quick Start →

Integrate in 4 Steps

Start authenticating users in minutes. This guide covers the Authorization Code flow — the most secure and recommended way.

1

Register your application

Go to the Developer Console and create an app. You'll get a client_id and client_secret.

2

Redirect user to authorization endpoint

Send the user to our authorize URL with the required params.

URL
GET /oidc/oauth2/authorize
  ?redirect_url=https://yourapp.com/callback
  &client_id=YOUR_CLIENT_ID
  &state=random_csrf_token
3

Exchange code for tokens

After login, user is redirected back with a code. Exchange it for tokens.

JavaScript
const response = await fetch('/oidc/oauth2/token', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    code: authCode,          // from redirect URL
    client_id: 'YOUR_CLIENT_ID',
    client_secret: 'YOUR_CLIENT_SECRET',
    grant_type: 'authorization_code',
  })
});

const result = await response.json();
const { accessToken, refreshToken, tokenType: "Bearer" } = result?.data;
4

Get user info

Use the access token to fetch the logged-in user's profile.

JavaScript
const response = await fetch('/oidc/oauth2/userinfo', {
  headers: { 'Authorization': `Bearer ${access_token}` }
})

const result = await response.json();
const { sub, name, email, exp } = result?.data;

What is OAuth 2.0?

OAuth 2.0 is an authorization framework. It lets your app access a user's data on their behalf — without ever knowing their password.

Think of it like a hotel key card. The hotel (authorization server) gives you a temporary card (access token) that opens only your room. You don't get a master key. The card expires. If you lose it, you get a new one — your actual credentials stay safe.

Authorization ≠ Authentication. OAuth 2.0 only answers "what can this app do?" — not "who is this user?". For identity, you need OIDC (below).

Key Roles

RoleWho it isExample
Resource OwnerThe userSomeone logging into your app
ClientYour applicationYour web / mobile app
Authorization ServerThis serverHandles login & issues tokens
Resource ServerThe APIUserinfo endpoint, your protected API

Grant Types Supported

Different ways an app can get tokens:

authorization_code refresh_token
Token Response
{
  "access_token":  "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type":    "Bearer",
  "expires_in":    "15m",
  "refresh_token": "def50200abc...",
  "scope":         "openid email profile"
}

What is OpenID Connect?

OpenID Connect (OIDC) is a thin identity layer on top of OAuth 2.0. It adds one key thing: an ID Token — a signed JWT that proves who the user is.

If OAuth 2.0 is the car key that opens the door, OIDC is the driver's license that proves who you are to begin with.

Always request openid scope to get an ID Token. Without it, you get OAuth 2.0 behaviour only — no identity info.

ID Token — What's inside?

The ID token is a JWT (JSON Web Token) signed with RS256. You can verify it using our public keys at /oidc/oauth2/certs.

JWT Payload (ID Token)
{
  "iss":      "https://intekhabx-auth.com",       // who issued this token
  "sub":      "user_abc123",               // unique user ID
  "aud":      "your_client_id",             // intended audience
  "exp":      1718000000,                  // expiry (unix timestamp)
  "email":    "user@example.com",
  "name":     "User",
}
Always verify the ID Token! Check iss, aud, and exp before trusting any claim. Use our JWKS endpoint to get the public key.

Authorization Code Flow

This is the standard, most secure flow. It keeps tokens out of the browser URL bar by using a short-lived code as an intermediary.

User clicks "Sign In" in your app.
Your app redirects to /oidc/oauth2/authorize with client_id, redirect_url, and a state value (for CSRF protection).
User logs in on our server (credentials never touch your app).
Server redirects back to your redirect_url with a one-time code in the query params.
Your backend exchanges the code at /oidc/oauth2/token using client_id + client_secret + code + grant_type. This happens server-side — secret never exposed to browser.
You receive access_token, refresh_token, and token_type.
Use access_token to call /oidc/oauth2/userinfo and get your user details.

Discovery Document

The discovery document (/.well-known/openid-configuration) is a standard OIDC endpoint that describes all our server's capabilities. Most OIDC libraries auto-discover configuration from here.

GET /.well-known/openid-configuration
{
  "issuer":                               "https://intekhabx-auth.onrender.com",
  "authorization_endpoint":               "https://intekhabx-auth.onrender.com/oidc/oauth2/authorize",
  "token_endpoint":                       "https://intekhabx-auth.onrender.com/oidc/oauth2/token",
  "userinfo_endpoint":                    "https://intekhabx-auth.onrender.com/oidc/oauth2/userinfo",
  "jwks_uri":                             "https://intekhabx-auth.onrender.com/oidc/oauth2/certs",
  "revocation_endpoint":                  "https://intekhabx-auth.onrender.com/oidc/oauth2/revoke",
  

  "response_types_supported":             ["code"],
  "response_modes_supported":             ["query", "form_post"],
  "subject_types_supported":             ["public"],
  "id_token_signing_alg_values_supported": ["RS256"],

  "scopes_supported":                     ["openid", "email", "profile"],
  "claims_supported": [
    "sub", "email", "name", "exp", "aud", "iss"
  ],
  "token_endpoint_auth_methods_supported": [
    "client_secret_post", "client_secret_basic"
  ],
  "grant_types_supported": [
    "authorization_code",
    "refresh_token",
  ]
}

Endpoints

MethodEndpointDescription
GET /.well-known/openid-configuration OIDC discovery document
GET /oidc/oauth2/authorize Start authorization — redirects user to login page
POST /oidc/oauth2/token Exchange code → tokens. Also use for refresh_token grant.
GET /oidc/oauth2/userinfo Get profile of logged-in user. Requires Bearer token.
GET /oidc/oauth2/certs JWKS — public keys for verifying JWTs
POST /oidc/oauth2/revoke Revoke access and refresh token and logout user

Refresh Token

When the access token expires (15 min), use the refresh token to get a new one without asking the user to log in again.

JavaScript — Refresh Token
const response = await fetch('/oidc/oauth2/token', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    grant_type:    'refresh_token',
    refresh_token: 'stored_Refresh_Token',
    client_id:     'YOUR_CLIENT_ID',
    client_secret: 'YOUR_CLIENT_SECRET',
  })
});

const result = await response.json();
const { accessToken, refreshToken, tokenType: "Bearer"} = result?.data;
// store new refresh_token — old one is now invalid

Scopes & Claims

Scopes control what data your app can access. Claims are the actual fields returned.

Scopes

ScopeWhat it unlocks
openidRequired. Enables OIDC — gives you an ID token with sub.
emailAdds email claim to the ID token and userinfo.
profileAdds name, ... to userinfo.

Claims

sub
Unique user identifier. Never changes.
email
User's email address.
name
Full name of the user.
exp
Total expires time of access_token.
iss
Token issuer URL.
aud
Audience — your client_id.

Token Types

TokenFormatLifetimePurpose
Access Token JWT ~15 min Call protected APIs. Send as Authorization: Bearer <token>
Refresh Token JWT Days / weeks Get new access tokens. Store securely. Rotate after use.
Never store tokens in localStorage. Use httpOnly cookies for refresh tokens on the server. For SPAs, keep access tokens in memory only.

PKCE — Proof Key for Code Exchange

🚧 Not yet implemented. PKCE support is planned for pure frontend / SPA use-cases where there is no backend server to keep the client_secret safe.

PKCE (pronounced "pixy") is a security extension to the Authorization Code flow. It was originally designed for mobile apps, but today it's the recommended approach for any public client — browser-only SPAs, mobile apps, CLI tools — where you cannot safely store a client secret.

Why do we need PKCE?

In the standard flow, your backend uses a client_secret to prove it's really your app when exchanging the authorization code. But in a pure frontend app, any secret you put in the JavaScript source code is visible to anyone who opens DevTools. PKCE replaces the secret with a one-time cryptographic proof.

Step 1 — Generate code_verifier

The code_verifier is a random, high-entropy string (43–128 characters) generated by your app at the start of each login attempt. It's like a temporary secret that only lives in memory for one login session.

JavaScript
// Generate a random code_verifier
function generateCodeVerifier() {
  const array = new Uint8Array(32);
  crypto.getRandomValues(array);
  return btoa(String.fromCharCode(...array))
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=/g,  '');
}

const codeVerifier = generateCodeVerifier();
// Example: "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
// Store in sessionStorage — needed after redirect
sessionStorage.setItem('pkce_verifier', codeVerifier);

Step 2 — Derive code_challenge

The code_challenge is a SHA-256 hash of the code_verifier, then Base64url-encoded. You send this to the authorization server at the start. The verifier stays secret; only the challenge (a hash) is sent in the URL.

JavaScript
async function generateCodeChallenge(verifier) {
  const data    = new TextEncoder().encode(verifier);
  const hash    = await crypto.subtle.digest('SHA-256', data);
  const bytes   = new Uint8Array(hash);
  return btoa(String.fromCharCode(...bytes))
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=/g,  '');
}

const codeChallenge = await generateCodeChallenge(codeVerifier);
// Example: "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
code_verifier (secret)
dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
→
SHA-256
+ base64url

→
code_challenge (sent in URL)
E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM

Step 3 — Send challenge with authorize request

Include the challenge and method in the initial redirect. No client_secret needed!

URL
GET /oidc/oauth2/authorize
  ?response_type=code
  &client_id=YOUR_CLIENT_ID
  &redirect_uri=https://yourapp.com/callback
  &scope=openid email profile
  &code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
  &code_challenge_method=S256   <-- always S256, not plain
  &state=random_csrf_token

Step 4 — Exchange code using verifier (no secret!)

When exchanging the code for tokens, send the code_verifier instead of a client_secret. The server verifies the hash matches the challenge it stored.

JavaScript — PKCE Token Exchange
const codeVerifier = sessionStorage.getItem('pkce_verifier');

const response = await fetch('/oidc/oauth2/token', {
  method: 'POST',
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  body: new URLSearchParams({
    grant_type:    'authorization_code',
    code:          authCode,
    client_id:     'YOUR_CLIENT_ID',
    redirect_uri:  'https://yourapp.com/callback',
    code_verifier: codeVerifier, // <-- this is the proof, no secret needed
  })
});
// server hashes codeVerifier, compares with stored code_challenge
// if they match → tokens issued. If not → 400 error.

Why is this secure?

Even if an attacker intercepts the authorization code from the redirect URL, they can't exchange it — because they don't have the code_verifier. Only your app that generated it can complete the exchange. The hash (challenge) is useless without the original random string.

When PKCE is implemented, you'll be able to build a complete login flow entirely in the browser — no backend server required. Perfect for static site deployments on Vercel, Netlify, GitHub Pages, etc.