Authenticate with private_key_jwt
Let your backend sign a short-lived JWT with its own private key instead of sending a sajn ID Inloggning client secret
With private_key_jwt, your backend proves who it is by signing a short-lived JWT, the client assertion, with a private key that never leaves your servers. sajn holds only the public key. There is no shared secret that can leak from sajn or from a log.
A client uses either a secret or keys, never both. The moment you switch a client to keys, its secret stops working.
Before you begin
- Your backend can sign a JWT with
ES256,ES384,PS256,RS256, orEdDSA. Most OIDC libraries supportprivate_key_jwt. - You decide how to switch:
- For a client that isn't live yet, switch it directly.
- For a live client, create a new client, set it up with keys, and move your app to it. A person keeps the same
subon every client in your organization, so your users don't notice the move.
1. Create a key pair
Create a key pair and give it a kid. This example uses jose and an EC P-256 key for ES256:
// create-key.mjs
import { exportJWK, generateKeyPair } from "jose";
const kid = "2026-11";
const { publicKey, privateKey } = await generateKeyPair("ES256", { extractable: true });
const publicJwks = { keys: [{ ...(await exportJWK(publicKey)), kid, alg: "ES256", use: "sig" }] };
const privateJwk = { ...(await exportJWK(privateKey)), kid, alg: "ES256" };
console.log("Register in sajn:\n" + JSON.stringify(publicJwks, null, 2));
console.log("Keep secret, in your backend:\n" + JSON.stringify(privateJwk));Store the private JWK in your backend's secret store. Never paste it into the sajn dashboard: sajn refuses a key that has private members such as d.
2. Register the public key
- In the sajn dashboard, go to Inställningar > Utvecklare > sajn ID Inloggning and open the client.
- Open the Uppgifter tab.
- Under Så autentiserar sig er backend, select Nycklar (private_key_jwt).
- In Publika nycklar (JWKS), paste the public JWKS, or click Ladda upp fil.
- Click Byt till nycklar, and confirm with Byt till nycklar.
The client's secret stops working at once, including a previous secret whose overlap still runs.
3. Send an assertion with each token request
Sign a new assertion for every token request:
import { randomUUID } from "node:crypto";
import { importJWK, SignJWT } from "jose";
const ISSUER = "https://id.sajn.se";
const CLIENT_ID = process.env.SAJN_CLIENT_ID;
const privateJwk = JSON.parse(process.env.SAJN_PRIVATE_JWK);
const privateKey = await importJWK(privateJwk, "ES256");
const clientAssertion = () =>
new SignJWT({})
.setProtectedHeader({ alg: "ES256", kid: privateJwk.kid })
.setIssuer(CLIENT_ID)
.setSubject(CLIENT_ID)
.setAudience(`${ISSUER}/oidc/token`)
.setJti(randomUUID())
.setIssuedAt()
.setExpirationTime("60s")
.sign(privateKey);
export const exchangeCode = async ({ code, redirectUri, codeVerifier }) => {
const response = await fetch(`${ISSUER}/oidc/token`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "authorization_code",
code,
redirect_uri: redirectUri,
code_verifier: codeVerifier,
client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
client_assertion: await clientAssertion(),
}),
});
const tokens = await response.json();
if (!response.ok) throw new Error(`${tokens.error}: ${tokens.error_description}`);
return tokens;
};The assertion must meet these rules:
issandsubare yourclient_id.audis one value:https://id.sajn.se/oidc/tokenorhttps://id.sajn.se.expis at most 5 minutes ahead.jtiis new for every assertion. sajn refuses an assertion whosejtiit has seen.
Don't send client_secret or an HTTP Basic header in the same request. sajn refuses a request that combines two methods with invalid_request.
If the token endpoint returns invalid_client, check these rules and the kid first. The response doesn't say which check failed. For every rule, see private_key_jwt.
Replace a key
The client holds up to 5 keys, so you can replace a key without downtime:
- Create a new key pair with a new
kid. - On the Uppgifter tab, add the new public key to the
keysarray next to the old one, and click Spara nycklar. - Deploy your backend with the new private key.
- Remove the old public key from the
keysarray, and click Spara nycklar.
Switch back to a secret
On the Uppgifter tab, select Hemlighet and click Byt till hemlighet. sajn creates a new secret and shows it once. The keys stop working at once.
Was this page helpful?
Last updated on