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.
Integrate in 4 Steps
Start authenticating users in minutes. This guide covers the Authorization Code flow — the most secure and recommended way.
Register your application
Go to the Developer Console and create an app. You'll get a client_id and client_secret.
Redirect user to authorization endpoint
Send the user to our authorize URL with the required params.
GET /oidc/oauth2/authorize ?redirect_url=https://yourapp.com/callback &client_id=YOUR_CLIENT_ID &state=random_csrf_token
Exchange code for tokens
After login, user is redirected back with a code. Exchange it for tokens.
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;
Get user info
Use the access token to fetch the logged-in user's profile.
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.
Key Roles
| Role | Who it is | Example |
|---|---|---|
| Resource Owner | The user | Someone logging into your app |
| Client | Your application | Your web / mobile app |
| Authorization Server | This server | Handles login & issues tokens |
| Resource Server | The API | Userinfo endpoint, your protected API |
Grant Types Supported
Different ways an app can get tokens:
{
"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.
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.
{
"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",
}
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.
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.
{
"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
| Method | Endpoint | Description |
|---|---|---|
| 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.
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
| Scope | What it unlocks |
|---|---|
| openid | Required. Enables OIDC — gives you an ID token with sub. |
Adds email claim to the ID token and userinfo. | |
| profile | Adds name, ... to userinfo. |
Claims
Token Types
| Token | Format | Lifetime | Purpose |
|---|---|---|---|
| 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. |
httpOnly cookies for refresh tokens on the server. For SPAs, keep access tokens in memory only.
PKCE — Proof Key for Code Exchange
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.
// 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.
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"
SHA-256
+ base64url
→
Step 3 — Send challenge with authorize request
Include the challenge and method in the initial redirect. No client_secret needed!
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.
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.