OIDC Authentication in PKI Manager
Source:
OIDC.md
This document explains how OpenID Connect (OIDC) authentication works between PKI Manager and identity providers like Keycloak.
Table of Contents
Section titled “Table of Contents”- Overview
- Public vs Confidential Clients
- The Authentication Flow
- PKCE: The Secret Replacement
- Token Validation
- Role-Based Access Control
- Docker Networking Considerations
- Machine-to-Machine Authentication
- Configuration Reference
- See Also
Overview
Section titled “Overview”PKI Manager uses OIDC for authentication with a public client architecture. This means:
- The frontend (React SPA) handles user login via the browser
- No client secret is used (secrets cannot be secured in browser code)
- PKCE (Proof Key for Code Exchange) provides security instead
- The backend only validates tokens - it never authenticates to Keycloak
Public vs Confidential Clients
Section titled “Public vs Confidential Clients”Why No Client Secret?
Section titled “Why No Client Secret?”A common question is: “Why don’t we use a client ID and client secret to identify the app?”
The answer lies in the nature of browser-based applications:
| Client Type | Where Code Runs | Can Store Secrets? | Authentication Method |
|---|---|---|---|
| Public (SPA, mobile) | Browser/device | No - code is visible | PKCE |
| Confidential (server) | Server | Yes - code is private | Client Secret |
PKI Manager’s frontend is a public client because:
- All JavaScript code is downloaded to and runs in the user’s browser
- Anyone can view the source code (DevTools → Sources)
- Any “secret” embedded in the code would be exposed
- Therefore, we cannot use a client secret
Instead, we use PKCE - a cryptographic proof that the same browser session that started the login is the one completing it.
Keycloak Client Configuration
Section titled “Keycloak Client Configuration”{ "clientId": "pki-web", "publicClient": true, "standardFlowEnabled": true, "attributes": { "pkce.code.challenge.method": "S256" }}publicClient: true- No secret requiredstandardFlowEnabled: true- Authorization Code Flowpkce.code.challenge.method: S256- Require PKCE with SHA-256
The Authentication Flow
Section titled “The Authentication Flow”Here’s the complete flow when a user logs into PKI Manager:
Step-by-Step Breakdown
Section titled “Step-by-Step Breakdown”- User clicks Login - Frontend initiates authentication
- Generate PKCE - Frontend creates a random
code_verifierand its SHA-256 hash (code_challenge) - Redirect to Keycloak - Browser goes to Keycloak with
code_challenge(not the verifier!) - Login form - Keycloak shows the login page
- Enter credentials - User authenticates with username/password
- Authorization code - Keycloak redirects back with a temporary code
- Exchange code - Frontend sends code +
code_verifierto get tokens - Receive tokens - Keycloak returns access token, refresh token, ID token
- API calls - Frontend includes
Authorization: Bearer <token>in requests - Validate token - Backend verifies signature using Keycloak’s public keys
- Authorized response - Backend returns data based on user’s roles
PKCE: The Secret Replacement
Section titled “PKCE: The Secret Replacement”PKCE (pronounced “pixy”) replaces the client secret with a one-time cryptographic proof.
How It Works
Section titled “How It Works”Why PKCE Is Secure
Section titled “Why PKCE Is Secure”| Attack Scenario | Protection |
|---|---|
| Attacker intercepts authorization code | Cannot use it without code_verifier |
Attacker tries to guess code_verifier |
256-bit entropy (impossible) |
Attacker intercepts code_challenge |
Cannot reverse SHA-256 hash |
| Replay attack | Each login uses new random code_verifier |
The code_verifier only leaves the browser memory once - when exchanging the code for tokens. By that point, it’s sent over HTTPS directly to Keycloak.
Token Validation
Section titled “Token Validation”The backend never authenticates to Keycloak. It only validates tokens using public key cryptography.
What the Backend Does
Section titled “What the Backend Does”// backend/src/lib/oidc.ts (discovery, JWKS) and backend/src/lib/jwt.ts (validation)
// 1. At startup: Fetch OIDC discovery documentconst discovery = await fetch( 'http://keycloak:8080/realms/pki-e2e/.well-known/openid-configuration');// Returns: { issuer, jwks_uri, token_endpoint, ... }
// 2. Get public keys (JWKS - JSON Web Key Set)const jwks = createRemoteJWKSet(new URL(discovery.jwks_uri));
// 3. For each request: Validate the tokenconst { payload } = await jwtVerify(token, jwks, { issuer: 'http://localhost:58180/realms/pki-e2e',});// then check that `aud` (or, as a fallback, `azp`) matches OIDC_AUDIENCE
// 4. Extract user info from token payloadconst userId = payload.sub;const email = payload.email;const roles = payload.realm_access?.roles; // ['admin'] or ['user']Token Structure
Section titled “Token Structure”A JWT (JSON Web Token) has three parts:
eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgxODAvcmVhbG1zL3BraS1lMmUiLCJhdWQiOiJwa2ktd2ViIiwic3ViIjoiMTIzNDU2Nzg5MCIsInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJhZG1pbiJdfX0.signature│ │ │└──────── Header ──────────────┴──────────────────────────────────── Payload ───────────────────────────────────────────────────────────────────────┴── Signature ──Decoded payload:
{ "iss": "http://localhost:58180/realms/pki-e2e", "aud": "pki-web", "sub": "user-uuid-here", "email": "testadmin@example.com", "realm_access": { "roles": ["admin", "user"] }, "exp": 1739456789, "iat": 1739453189}Validation Steps
Section titled “Validation Steps”- Signature verification - Using Keycloak’s public RSA key
- Issuer check -
issmust match configuredOIDC_ISSUER - Audience check -
aud(or, as a fallback,azp) must match one of the configuredOIDC_AUDIENCEvalues - Expiration check -
expmust be in the future - Not-before check -
nbf, when present, must be in the past
Role-Based Access Control
Section titled “Role-Based Access Control”PKI Manager uses Keycloak realm roles for authorization:
| Role | Permissions |
|---|---|
user |
View CAs and certificates, issue certificates, download |
admin |
All user permissions + create/revoke/delete CAs and certificates |
How Roles Flow Through the System
Section titled “How Roles Flow Through the System”Backend Middleware
Section titled “Backend Middleware”// backend/src/trpc/init.ts and backend/src/trpc/middleware/auth.ts (simplified)
// Protected procedure - any authenticated userexport const protectedProcedure = t.procedure.use(authMiddleware);
// Admin procedure - requires 'admin' roleexport const adminProcedure = protectedProcedure.use(async ({ ctx, next }) => { if (!ctx.user.roles.includes('admin')) { throw new TRPCError({ code: 'FORBIDDEN', message: 'Admin role required' }); } return next({ ctx });});Docker Networking Considerations
Section titled “Docker Networking Considerations”When running in Docker, there’s a networking challenge:
- Browser accesses Keycloak at
localhost:58180 - Backend container cannot reach
localhost:58180(it refers to itself) - Tokens have
iss: http://localhost:58180/realms/pki-e2e
Solution: OIDC_DISCOVERY_BASE_URL
Section titled “Solution: OIDC_DISCOVERY_BASE_URL”Configuration:
backend: environment: # What's in tokens (for validation) - OIDC_ISSUER=http://localhost:58180/realms/pki-e2e # Where to fetch OIDC config (Docker network) - OIDC_DISCOVERY_BASE_URL=http://keycloak:8080/realms/pki-e2eMachine-to-Machine Authentication
Section titled “Machine-to-Machine Authentication”For server-to-server communication without user interaction, use a confidential client:
When to use this:
- CI/CD pipelines issuing certificates
- Automated certificate renewal services
- Integration with other systems
Keycloak setup:
- Create client
pki-servicewithpublicClient: false - Enable “Service accounts roles”
- Assign appropriate roles
- Get client secret from Credentials tab
Configuration Reference
Section titled “Configuration Reference”Backend Environment Variables
Section titled “Backend Environment Variables”| Variable | Required | Description |
|---|---|---|
OIDC_ISSUER |
Yes | Token issuer URL (must match iss claim) |
OIDC_AUDIENCE |
Yes | Expected audience(s), comma-separated |
OIDC_ROLES_CLAIM |
No | Path to roles in token (default: realm_access.roles) |
OIDC_DISCOVERY_BASE_URL |
No | Override URL for fetching OIDC config |
OIDC_ROLES_SOURCE |
No | token (default) or userinfo: where roles are read from |
Frontend Environment Variables
Section titled “Frontend Environment Variables”| Variable | Required | Description |
|---|---|---|
VITE_OIDC_AUTHORITY |
Yes | OIDC provider URL (same as OIDC_ISSUER) |
VITE_OIDC_CLIENT_ID |
Yes | Public client ID (e.g., pki-web) |
VITE_OIDC_SCOPE |
No | OAuth scopes (default: openid profile email) |
The redirect URI is <origin>/callback, the post-logout URI is <origin>/ and silent renewal uses <origin>/silent-renew.html.
Example Configuration
Section titled “Example Configuration”# BackendOIDC_ISSUER=https://keycloak.example.com/realms/pkiOIDC_AUDIENCE=pki-web,pki-serviceOIDC_ROLES_CLAIM=realm_access.roles
# Frontend (build-time or runtime config.json)VITE_OIDC_AUTHORITY=https://keycloak.example.com/realms/pkiVITE_OIDC_CLIENT_ID=pki-webComparison Summary
Section titled “Comparison Summary”| Aspect | Public Client (pki-web) | Confidential Client (pki-service) |
|---|---|---|
| Use case | Browser SPA | Server-side automation |
| Secret | None (uses PKCE) | Required |
| User interaction | Yes (login form) | No |
| Token exchange | Browser → Keycloak | Server → Keycloak |
| Security mechanism | PKCE cryptographic proof | Shared secret |
| Grant type | Authorization Code + PKCE | Client Credentials |
See Also
Section titled “See Also”- KEYCLOAK.md - Step-by-step Keycloak configuration with screenshots
- DEPLOYMENT.md - Docker deployment including OIDC configuration
- DEPLOYMENT.md#e2e-testing - E2E testing with pre-configured Keycloak