Examples
All examples follow the same procedure: they send the user to sign in with Certilia with PKCE (S256), state and
nonce, on the way back exchange the code for tokens, check the ID token (signature, issuer, audience, expiry and
nonce) and show the data about the user from it. A standard OpenID Connect library does all of this and needs only
the values from the Integration tab on the application’s page; the examples read them from environment variables:
| Variable | Value |
|---|---|
CERTILIA_ISSUER |
Issuer, on the test system https://idp.test.certilia.com/oauth2/token. The library adds /.well-known/openid-configuration to it (OpenID Discovery). |
CERTILIA_CLIENT_ID |
Client ID. |
CERTILIA_CLIENT_SECRET |
Client Secret. Read it from your environment’s secrets, never from code. |
SESSION_SECRET |
Only for Node.js and Python: a long random value the example signs its session cookie with. |
Each example runs on a separate port on your computer. In the application’s settings, under Redirect URIs, enter
the address of the example you are trying (HTTP is allowed only for localhost) and then open its sign-in address in
the browser:
| Example | Redirect URI | Sign-in |
|---|---|---|
| Java | http://localhost:3104/login/oauth2/code/certilia |
http://localhost:3104/ |
| .NET | http://localhost:3103/callback |
http://localhost:3103/login |
| Python | http://localhost:3105/callback |
http://localhost:3105/login |
| Node.js | http://localhost:3101/callback |
http://localhost:3101/login |
| PHP | http://localhost:3102/callback |
http://localhost:3102/login |
| Go | http://localhost:3106/callback |
http://localhost:3106/login |
After the sign-in the example shows the data from the ID token as JSON. Identify the user by sub (the OIB). The
first name, last name and e-mail address come as given_name, family_name and email when the application asks
for them and the user approved them.
Java 25, Spring Boot 4.1.2 with Spring Security (OAuth2 Client) and Maven.
Spring adds state and nonce automatically, and OAuth2AuthorizationRequestCustomizers.withPkce() turns on PKCE for
a server application.
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>4.1.2</version> </parent> <groupId>com.example</groupId> <artifactId>certilia-sign-in</artifactId> <version>1.0.0</version> <properties> <java.version>25</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webmvc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security-oauth2-client</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build></project>server: port: 3104spring: security: oauth2: client: registration: certilia: client-id: ${CERTILIA_CLIENT_ID} client-secret: ${CERTILIA_CLIENT_SECRET} scope: openid provider: certilia: issuer-uri: ${CERTILIA_ISSUER}package com.example;
import java.util.Map;
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.Bean;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.core.annotation.AuthenticationPrincipal;import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;import org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizationRequestResolver;import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestCustomizers;import org.springframework.security.oauth2.core.oidc.user.OidcUser;import org.springframework.security.web.SecurityFilterChain;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication@RestControllerpublic class CertiliaSignIn {
public static void main(String[] args) { SpringApplication.run(CertiliaSignIn.class, args); }
// Every page needs a sign-in; Spring sends the user to Certilia with PKCE (S256), state and nonce, // and on /login/oauth2/code/certilia exchanges the code for tokens and checks the ID token. @Bean SecurityFilterChain security(HttpSecurity http, ClientRegistrationRepository registrations) throws Exception { var resolver = new DefaultOAuth2AuthorizationRequestResolver(registrations, "/oauth2/authorization"); resolver.setAuthorizationRequestCustomizer(OAuth2AuthorizationRequestCustomizers.withPkce()); http.authorizeHttpRequests(requests -> requests.anyRequest().authenticated()) .oauth2Login(login -> login.authorizationEndpoint(endpoint -> endpoint.authorizationRequestResolver(resolver))); return http.build(); }
@GetMapping("/") Map<String, Object> user(@AuthenticationPrincipal OidcUser user) { return user.getIdToken().getClaims(); }}mvn packagejava -jar target/certilia-sign-in-1.0.0.jar.NET 10 (LTS), package Microsoft.AspNetCore.Authentication.OpenIdConnect 10.0.15. The middleware uses PKCE, state
and nonce automatically, and Certilia sends the user back to it with a POST request to /callback
(response_mode=form_post). It reads the environment variables through builder.Configuration.
<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>net10.0</TargetFramework> <Nullable>enable</Nullable> <ImplicitUsings>enable</ImplicitUsings> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="10.0.15" /> </ItemGroup></Project>using Microsoft.AspNetCore.Authentication;using Microsoft.AspNetCore.Authentication.Cookies;using Microsoft.AspNetCore.Authentication.OpenIdConnect;
var builder = WebApplication.CreateBuilder(args);
builder.Services .AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }) .AddCookie() .AddOpenIdConnect(options => { // The middleware reads the endpoints and keys from the Discovery document. options.Authority = builder.Configuration["CERTILIA_ISSUER"]; options.ClientId = builder.Configuration["CERTILIA_CLIENT_ID"]; options.ClientSecret = builder.Configuration["CERTILIA_CLIENT_SECRET"]; options.ResponseType = "code"; options.UsePkce = true; options.CallbackPath = "/callback"; options.Scope.Clear(); options.Scope.Add("openid"); options.MapInboundClaims = false; });
var app = builder.Build();app.UseAuthentication();
app.MapGet("/", (HttpContext http) => http.User.Identity?.IsAuthenticated == true ? Results.Json(http.User.Claims.Select(claim => new { claim.Type, claim.Value })) : Results.Content("<a href=\"/login\">Sign in with Certilia</a>", "text/html"));
// The middleware sends the user to Certilia, and on /callback exchanges the code for tokens and checks the ID token.app.MapGet("/login", () => Results.Challenge(new AuthenticationProperties { RedirectUri = "/" }));
app.Run("http://localhost:3103");dotnet runPython 3.15, Flask 3.1.3 and Authlib 1.9.8 (with
requests 2.34.2). code_challenge_method in client_kwargs turns on PKCE, and Authlib adds state and nonce
automatically.
pip install Flask==3.1.3 Authlib==1.9.8 requests==2.34.2import os
from authlib.integrations.flask_client import OAuthfrom flask import Flask, redirect, session
app = Flask(__name__)app.secret_key = os.environ["SESSION_SECRET"]
# Authlib reads the endpoints and keys from the Discovery document.oauth = OAuth(app)oauth.register( "certilia", client_id=os.environ["CERTILIA_CLIENT_ID"], client_secret=os.environ["CERTILIA_CLIENT_SECRET"], server_metadata_url=os.environ["CERTILIA_ISSUER"] + "/.well-known/openid-configuration", client_kwargs={"scope": "openid", "code_challenge_method": "S256"},)
@app.get("/")def home(): if "user" in session: return session["user"] return '<a href="/login">Sign in with Certilia</a>'
@app.get("/login")def login(): return oauth.certilia.authorize_redirect("http://localhost:3105/callback")
@app.get("/callback")def callback(): # Checks state, exchanges the code for tokens and checks the ID token (signature, iss, aud, exp, nonce). token = oauth.certilia.authorize_access_token() session.clear() session["user"] = token["userinfo"] return redirect("/")
if __name__ == "__main__": app.run(port=3105)python app.pyNode.js 26, openid-client 6.9.0, Express 5.3.0 and express-session 1.19.0.
{ "name": "certilia-sign-in", "private": true, "type": "module", "dependencies": { "express": "5.3.0", "express-session": "1.19.0", "openid-client": "6.9.0" }}import express from "express";import session from "express-session";import * as oidc from "openid-client";
const redirectUri = "http://localhost:3101/callback";
// The library reads the endpoints and keys from the Discovery document.const config = await oidc.discovery( new URL(process.env.CERTILIA_ISSUER), process.env.CERTILIA_CLIENT_ID, undefined, oidc.ClientSecretBasic(process.env.CERTILIA_CLIENT_SECRET),);
const app = express();app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false, cookie: { httpOnly: true, sameSite: "lax" } }));
app.get("/", (req, res) => { if (req.session.user) res.json(req.session.user); else res.send('<a href="/login">Sign in with Certilia</a>');});
app.get("/login", async (req, res) => { const codeVerifier = oidc.randomPKCECodeVerifier(); const state = oidc.randomState(); const nonce = oidc.randomNonce(); req.session.login = { codeVerifier, state, nonce }; const url = oidc.buildAuthorizationUrl(config, { redirect_uri: redirectUri, scope: "openid", state, nonce, code_challenge: await oidc.calculatePKCECodeChallenge(codeVerifier), code_challenge_method: "S256", }); res.redirect(url.href);});
app.get("/callback", async (req, res) => { const login = req.session.login; if (!login) return res.redirect("/"); // Checks state, exchanges the code for tokens and checks the ID token (signature, iss, aud, exp, nonce). const tokens = await oidc.authorizationCodeGrant(config, new URL(req.originalUrl, redirectUri), { pkceCodeVerifier: login.codeVerifier, expectedState: login.state, expectedNonce: login.nonce, }); const user = tokens.claims(); req.session.regenerate(() => { req.session.user = user; res.redirect("/"); });});
app.listen(3101);npm installnode server.jsPHP 8.5 with the curl, openssl and mbstring extensions,
jumbojett/openid-connect-php 1.0.2 (Composer). The library keeps
state, nonce and code_verifier in the PHP session. Its latest release reports deprecations on PHP 8.4 and later,
so the example does not print them.
{ "require": { "php": ">=8.5", "jumbojett/openid-connect-php": "1.0.2" }}<?php// jumbojett 1.0.2 reports deprecations on PHP 8.4 and later; printed, they would break the redirect.error_reporting(E_ALL & ~E_DEPRECATED);require __DIR__ . '/vendor/autoload.php';
use Jumbojett\OpenIDConnectClient;
session_start();$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
if ($path === '/login' || $path === '/callback') { // The library reads the endpoints and keys from the Discovery document. $oidc = new OpenIDConnectClient(getenv('CERTILIA_ISSUER'), getenv('CERTILIA_CLIENT_ID'), getenv('CERTILIA_CLIENT_SECRET')); $oidc->setRedirectURL('http://localhost:3102/callback'); $oidc->setCodeChallengeMethod('S256'); // On /login it redirects to Certilia; on /callback it checks state, exchanges the code for tokens and checks the ID token. $oidc->authenticate(); session_regenerate_id(true); $_SESSION['user'] = $oidc->getVerifiedClaims(); header('Location: /'); exit;}
if (isset($_SESSION['user'])) { header('Content-Type: application/json'); echo json_encode($_SESSION['user'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);} else { echo '<a href="/login">Sign in with Certilia</a>';}composer installphp -S localhost:3102 index.phpGo 1.27, go-oidc 3.21.0 and golang.org/x/oauth2
0.38.0. The example keeps state, nonce and code_verifier in short-lived HttpOnly cookies and shows the data
about the user immediately on the way back. Open your own session at the point marked in the code.
go mod init example.com/certilia-sign-ingo get github.com/coreos/go-oidc/v3@v3.21.0 golang.org/x/oauth2@v0.38.0go mod tidypackage main
import ( "context" "crypto/rand" "encoding/json" "log" "net/http" "os"
"github.com/coreos/go-oidc/v3/oidc" "golang.org/x/oauth2")
func main() { // go-oidc reads the endpoints and keys from the Discovery document. provider, err := oidc.NewProvider(context.Background(), os.Getenv("CERTILIA_ISSUER")) if err != nil { log.Fatal(err) } config := oauth2.Config{ ClientID: os.Getenv("CERTILIA_CLIENT_ID"), ClientSecret: os.Getenv("CERTILIA_CLIENT_SECRET"), Endpoint: provider.Endpoint(), RedirectURL: "http://localhost:3106/callback", Scopes: []string{oidc.ScopeOpenID}, } verifier := provider.Verifier(&oidc.Config{ClientID: config.ClientID})
http.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`<a href="/login">Sign in with Certilia</a>`)) })
http.HandleFunc("GET /login", func(w http.ResponseWriter, r *http.Request) { state, nonce, codeVerifier := rand.Text(), rand.Text(), oauth2.GenerateVerifier() setCookie(w, r, "state", state) setCookie(w, r, "nonce", nonce) setCookie(w, r, "verifier", codeVerifier) url := config.AuthCodeURL(state, oidc.Nonce(nonce), oauth2.S256ChallengeOption(codeVerifier)) http.Redirect(w, r, url, http.StatusFound) })
http.HandleFunc("GET /callback", func(w http.ResponseWriter, r *http.Request) { state, err1 := r.Cookie("state") nonce, err2 := r.Cookie("nonce") codeVerifier, err3 := r.Cookie("verifier") if err1 != nil || err2 != nil || err3 != nil || r.URL.Query().Get("state") != state.Value { http.Error(w, "The sign-in failed, please try again.", http.StatusBadRequest) return } token, err := config.Exchange(r.Context(), r.URL.Query().Get("code"), oauth2.VerifierOption(codeVerifier.Value)) if err != nil { http.Error(w, "The code exchange failed.", http.StatusBadGateway) return } rawIDToken, _ := token.Extra("id_token").(string) // Checks the signature, iss, aud and exp; we check the nonce ourselves. idToken, err := verifier.Verify(r.Context(), rawIDToken) if err != nil || idToken.Nonce != nonce.Value { http.Error(w, "The ID token is not valid.", http.StatusUnauthorized) return } var claims map[string]any idToken.Claims(&claims) // Open your own session for the user here (the identifier is idToken.Subject). w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(claims) })
log.Fatal(http.ListenAndServe("localhost:3106", nil))}
func setCookie(w http.ResponseWriter, r *http.Request, name, value string) { http.SetCookie(w, &http.Cookie{ Name: name, Value: value, Path: "/", MaxAge: 600, HttpOnly: true, Secure: r.TLS != nil, SameSite: http.SameSiteLaxMode, })}go run .An application in the browser must not contain the client secret, so it signs in through its own server (the
Backend for Frontend pattern, see the guide).
The server is the Node.js example from the Node.js tab: it performs the sign-in and gives the browser only a session
cookie. Add serving the SPA from the public folder and a route with the signed-in user’s data, and delete its /
route (the SPA’s index.html now takes over that role). The redirect URI stays http://localhost:3101/callback.
// The SPA from the public folder; the example's / route is gone.app.use(express.static("public"));
// The signed-in user's data from the session; the tokens stay on the server.app.get("/api/me", (req, res) => { if (req.session.user) res.json(req.session.user); else res.sendStatus(401);});<!doctype html><html lang="en"> <head> <meta charset="utf-8" /> <title>Sign in with Certilia</title> </head> <body> <a id="login" href="/login" hidden>Sign in with Certilia</a> <pre id="user"></pre> <script type="module" src="/main.js"></script> </body></html>// The browser sends the session cookie by itself; the SPA sees neither the secret nor the tokens.const response = await fetch("/api/me");if (response.ok) { document.querySelector("#user").textContent = JSON.stringify(await response.json(), null, 2);} else { document.querySelector("#login").hidden = false;}node server.jsThen open http://localhost:3101/.
The client secret can be extracted without difficulty from a mobile app’s installation package, so your server finishes the sign-in (see the guide):
- The app opens the sign-in in the system browser, never in a WebView: Custom Tabs on Android (for example through
AppAuth-Android 0.11.1),
ASWebAuthenticationSessionon iOS. It opens your server’s sign-in address, for examplehttps://your-domain.com/login. - The server sends the user to Certilia with PKCE,
stateandnonce, as in the examples on the other tabs. The redirect URI is an address on your server, for examplehttps://your-domain.com/callback. - On the way back the server exchanges the code for tokens with the client secret, validates the ID token and
redirects the user to your app’s Android App Link or iOS Universal Link, for example
https://your-domain.com/app/signed-in?ticket=<one-time value>.ASWebAuthenticationSessionaccepts an HTTPS callback from iOS 17.4. - The app exchanges that one-time, short-lived value at your server for its own session. Certilia’s tokens and the client secret stay on the server.