Add login without a library
Send the authorization request, check the callback, and exchange the code for tokens with Proof Key for Code Exchange (PKCE) and no login library.
Use this flow when the oidc-spa library does not fit your application. ID
token validation still needs a maintained OpenID Connect (OIDC) library.
Prerequisites
- An approved Login client and its client ID.
- A callback URL that is registered exactly for the client. This example uses
https://yourapp.example/callback. - The authorization request parameters and the token response fields.
- The login button kit, for the button that starts login.
Steps
-
Read the endpoint URLs from the discovery document at runtime:
https://www.remilia.net/oidc/realms/remilia/.well-known/openid-configuration -
Generate a random
state, a randomnonce, a PKCE verifier, and itsS256challenge:// base64url-encode raw bytes with no padding, as RFC 7636 requires. function base64url(bytes) { return btoa(String.fromCharCode(...bytes)) .replace(/\+/g, "-") .replace(/\//g, "_") .replace(/=+$/, ""); } const state = base64url(crypto.getRandomValues(new Uint8Array(16))); const nonce = base64url(crypto.getRandomValues(new Uint8Array(16))); const verifier = base64url(crypto.getRandomValues(new Uint8Array(32))); const digest = await crypto.subtle.digest( "SHA-256", new TextEncoder().encode(verifier), ); const challenge = base64url(new Uint8Array(digest)); -
Save
state,nonce, and the verifier before you redirect:sessionStorage.setItem("oauth_state", state); sessionStorage.setItem("oauth_nonce", nonce); sessionStorage.setItem("pkce_verifier", verifier); -
Redirect the user to
authorization_endpointwith the authorization parameters:const params = new URLSearchParams({ client_id: "YOUR_CLIENT_ID", response_type: "code", redirect_uri: "https://yourapp.example/callback", scope: "openid", state, nonce, code_challenge: challenge, code_challenge_method: "S256", }); window.location.assign( "https://www.remilia.net/oidc/realms/remilia/protocol/openid-connect/auth" + `?${params}`, ); -
Consume the saved login transaction when the callback loads:
const url = new URL(window.location.href); const params = new URLSearchParams(url.search); const expectedState = sessionStorage.getItem("oauth_state"); const verifier = sessionStorage.getItem("pkce_verifier"); const expectedNonce = sessionStorage.getItem("oauth_nonce"); sessionStorage.removeItem("oauth_state"); sessionStorage.removeItem("pkce_verifier"); sessionStorage.removeItem("oauth_nonce"); -
Remove the authorization response parameters from the address bar:
const responseKeys = [ "code", "state", "error", "error_description", "session_state", "iss", ]; for (const key of responseKeys) { url.searchParams.delete(key); } window.history.replaceState(null, "", url.pathname + url.search + url.hash); -
Reject the callback unless it returns exactly the saved
state:const states = params.getAll("state"); if (!expectedState || states.length !== 1 || states[0] !== expectedState || !verifier || !expectedNonce) { throw new Error("Login could not be verified. Log in again."); } -
Reject a callback that returns an error, no code, or more than one value:
const errors = params.getAll("error"); const codes = params.getAll("code"); if (errors.length > 1 || codes.length > 1 || (errors.length && codes.length)) { throw new Error("The login response was invalid. Log in again."); } if (errors.length) { throw new Error("Login was not completed. Log in again."); } if (codes.length !== 1 || !codes[0]) { throw new Error("No authorization code was returned. Log in again."); } const code = codes[0]; -
Exchange the code and the verifier at
token_endpoint:const res = await fetch( "https://www.remilia.net/oidc/realms/remilia/protocol/openid-connect/token", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ grant_type: "authorization_code", client_id: "YOUR_CLIENT_ID", code, // The redirect_uri must match step 4. redirect_uri: "https://yourapp.example/callback", code_verifier: verifier, }), }, ); if (!res.ok) { throw new Error(`token exchange failed: ${res.status}`); } const tokens = await res.json(); -
Validate the ID token with a maintained OIDC library before you use its claims.
-
Send the access token as a bearer token to
/api/v1:curl https://www.remilia.net/api/v1/me \ -H "Authorization: Bearer $ACCESS_TOKEN"
Result
Your app holds an access token, an ID token, and, when the provider issues one,
a refresh token. tokens.scope lists the scopes that your client was granted. A
call to an endpoint whose scope is outside that grant fails with
insufficient_scope.
The ID token rules list the checks of step 10. An app
that only calls /api/v1 sends the access token and reads no identity from the
ID token. Your app keeps the tokens in the storage that it chose. For more
information, see Token storage.
Troubleshooting
If the callback check or the code exchange fails, start another login from step 2. For each error code, see Login and API requests fail.
Example
This curl command makes the same code exchange as step 9:
curl -X POST \
https://www.remilia.net/oidc/realms/remilia/protocol/openid-connect/token \
-d grant_type=authorization_code \
-d client_id=YOUR_CLIENT_ID \
-d code=AUTHORIZATION_CODE \
-d redirect_uri=https://yourapp.example/callback \
-d code_verifier=YOUR_PKCE_VERIFIERNext steps
- Refresh an access token before it expires.
- Log a user out of your app and clear the stored tokens.
