Making a stolen access token useless: DPoP with Angular, oidc-spa, Keycloak and Spring Boot

My SPA security checklist used to stop at "authorization code flow with PKCE, short-lived tokens". Then I asked: if someone copies an access token out of the browser, what stops them from using it?
Nothing. This post shows how I closed that gap with DPoP.
The problem with bearer tokens
A bearer token works for whoever holds it. The API cannot tell the logged-in browser apart from a script that copied the token.
In a SPA the token lives in JavaScript. One XSS hole or one compromised npm package can read it and send it elsewhere. The attacker then calls your API from their own machine until the token expires.
Short lifetimes shrink that window. They don't close it.
What DPoP is
DPoP, "Demonstrating Proof of Possession" (RFC 9449), is an OAuth 2.0 extension that makes access tokens sender-constrained: only the client that requested a token can use it. It does this with asymmetric cryptography at the application layer, using plain HTTP headers and JWTs. There is no TLS client certificate like in mTLS (RFC 8705), which is why it works in a browser.
The idea fits in five steps:
- The SPA generates a key pair (typically ES256) and keeps the private key.
- When requesting tokens, it sends a signed JWT called a DPoP proof, which contains the public key.
- Keycloak binds the access token to that key by putting the key's thumbprint in the
cnf.jktclaim. - On every API call, the SPA sends the token and a fresh proof.
- The API checks the proof and that its key matches
cnf.jkt.
The DPoP proof
A proof is a short-lived JWT sent in the DPoP HTTP header. It is signed with the private key, and the matching public key travels inside it, so anyone can verify the signature but only the key holder can produce one.
Header
| Field | Value |
|---|---|
typ |
Always dpop+jwt. |
alg |
An asymmetric algorithm, e.g. ES256 or RS256. |
jwk |
The client's public key. Never the private key. |
Payload
| Claim | Meaning |
|---|---|
jti |
Unique ID of this proof. Lets the server reject a proof it has already seen. |
htm |
HTTP method of the request: POST for the token endpoint, GET for a read. |
htu |
Target URL, without query string or fragment. |
iat |
When the proof was created. Old proofs are rejected. |
ath |
API calls only: base64url SHA-256 hash of the access token it accompanies. |
nonce |
Optional. A value the server sent earlier, to prove the proof is fresh. |
A proof for an API call looks like this:
{
"jti": "b1f6c0c2-6c1e-4c57-9d0e-0f6d9a6e2a11",
"htm": "GET",
"htu": "http://localhost:8081/api/orders",
"iat": 1794838800,
"ath": "fUHyO2r2Z3DZ53EsNrWBb0xWXoaNy59IiKCAqksmQEo"
}
Here is a real proof from my app, decoded with jwt.io. The three colors on the left are the header, payload and signature. On the right you can see the public key in jwk and the request it was signed for.

Each proof is valid for one method, one URL and one token. Capturing it in transit doesn't let you reuse it elsewhere.
How the token gets bound
The SPA sends a proof with htm: POST and the token endpoint's URL to Keycloak's /token endpoint. If the proof is valid, Keycloak:
- adds a confirmation claim to the access token:
"cnf": { "jkt": "(RFC 7638 thumbprint);" } - returns
"token_type": "DPoP"instead of"Bearer"; - binds the refresh token to the same key, so a stolen refresh token is just as useless.
The client then uses Authorization: DPoP instead of Authorization: Bearer .
What the API verifies
On every request, the resource server checks that:
- the
DPoPheader holds exactly one well-formed JWT withtyp: dpop+jwtand an asymmetricalg; - the signature is valid for the
jwkin its header; htmandhtumatch the current request;iatis recent andjtihasn't been used before;athequals the hash of the access token inAuthorization;- the thumbprint of
jwkequalscnf.jktin the access token.
Only then does normal JWT validation (issuer, expiry, audience, roles) decide the rest.
Nonces
A server can require a nonce in the proof to limit how far in advance proofs can be created. It rejects the first request (use_dpop_nonce: 400 from the token endpoint, 401 from an API) and sends a value in a DPoP-Nonce response header. The client signs a new proof including that nonce and retries. oidc-spa handles this for you, including retries.
Why a stolen token is now useless
The attacker has the token but not the private key. They cannot sign a proof whose key matches cnf.jkt, so every request fails. A proof captured with the token doesn't help either, since it is tied to one method, one URL and a few seconds.
This only holds as long as the private key cannot be copied. A good client library creates it as a non-extractable WebCrypto key, so even JavaScript running in the page can use it but cannot read it out.
The whole flow
Step 1: Keycloak
DPoP is officially supported from Keycloak 26.4. No feature flag needed.
Use a normal public SPA client (standard flow, PKCE S256, redirect URIs and web origins set). Then, in Settings → Capability config, turn on Require DPoP bound tokens.
Good to know: with the switch off, Keycloak still binds tokens for clients that send a proof. The switch only rejects clients that don't. Leave it off during migration, turn it on at the end.
Step 2: Angular with oidc-spa
oidc-spa handles DPoP for you: key generation, signing, token hashing and nonces. Don't write that by hand.
oidc-spa must run before any other script, so the app moves to main.lazy.ts and main.ts becomes:
// src/main.ts
import { oidcEarlyInit } from "oidc-spa/entrypoint";
import { browserRuntimeFreeze } from "oidc-spa/browser-runtime-freeze";
import { DPoP } from "oidc-spa/DPoP";
const { shouldLoadApp } = oidcEarlyInit({
securityDefenses: {
...browserRuntimeFreeze(),
...DPoP({ mode: "auto" }),
},
});
if (shouldLoadApp) {
import("./main.lazy");
}
auto: use DPoP if the provider supports it, otherwise fall back to bearer.enforced: refuse to start without DPoP.
Start with auto, move to enforced once it works.
DPoP is off by default in oidc-spa, unlike PKCE, because many APIs can't validate DPoP-bound tokens yet. Once it's on, an API that doesn't support DPoP rejects the calls instead of silently falling back to bearer. If your app talks to such an API, opt that client out with createOidc({ disableDPoP: true }). If you use oidc-spa's Vite plugin, you can enable DPoP there instead (DPoP: { enabled: true, mode: "auto" }).
The rest is the standard oidc-spa setup:
// src/app/services/oidc.service.ts
import { Injectable } from "@angular/core";
import { AbstractOidcService } from "oidc-spa/angular";
export type DecodedIdToken = { name: string };
@Injectable({ providedIn: "root" })
export class Oidc extends AbstractOidcService<DecodedIdToken> {}
// src/app/app.config.ts
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(
withInterceptors([
Oidc.createBearerInterceptor({
shouldInjectAccessToken: (req) =>
req.url.startsWith("http://localhost:8081/api"),
}),
]),
),
provideRouter(routes),
Oidc.provide({
issuerUri: "http://localhost:8080/realms/demo",
clientId: "angular-spa",
}),
],
};
Despite its name, the bearer interceptor works with DPoP. oidc-spa rewrites the request to Authorization: DPoP and adds the proof header. Your application code doesn't change.
In the Network tab, each API call now has two headers:
GET /api/orders HTTP/1.1
Host: localhost:8081
Authorization: DPoP eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...
DPoP: eyJ0eXAiOiJkcG9wK2p3dCIsImFsZyI6IkVTMjU2IiwiandrIjp7...
The DPoP header decodes to {"typ":"dpop+jwt","alg":"ES256","jwk":{.... That's the proof.

Step 3: Spring Boot
Spring Security validates DPoP tokens since 6.5, but the default changed:
| Spring Security | What you need |
|---|---|
| 6.5 and 7.0 | Nothing. Enabled automatically with jwt(). |
| 7.1 and later | .dPoP(Customizer.withDefaults()). Opt-in. |
Most tutorials target 6.5. On 7.1+, without dPoP(), every Authorization: DPoP ... request is rejected.
Issuer config, as usual:
# application.yml
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: http://localhost:8080/realms/demo
Security configuration:
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
@Value("${application.cors.allowed-origins:*}")
private List<String> allowedOrigins;
@Bean
public SecurityFilterChain jwtAuthorizationSecurityFilterChain(HttpSecurity http) {
return http.cors(Customizer.withDefaults())
// no CSRF protection needed for token based authentication
.csrf(AbstractHttpConfigurer::disable)
// tokens are checked on every request, no session
.sessionManagement(
session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(
request -> {
// let a failing endpoint answer with its own error
// instead of turning every 500 into a 401
request.dispatcherTypeMatchers(DispatcherType.ERROR).permitAll();
request.anyRequest().authenticated();
})
.oauth2ResourceServer(
oauth2 ->
oauth2.jwt(
token ->
token.jwtAuthenticationConverter(
new KeycloakJwtAuthenticationConverter()))
// also accept tokens bound to a key of the client
// (DPoP, RFC 9449)
.dPoP(Customizer.withDefaults()))
.build();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.setAllowedOriginPatterns(allowedOrigins);
config.setAllowedHeaders(List.of("*"));
config.setAllowedMethods(List.of("*"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}
}
Key points:
jwt()stays. DPoP adds to JWT validation, it doesn't replace it. Custom converters (here, Keycloak roles → authorities) keep working..dPoP(...)is the only DPoP-specific line in the backend.- CORS must allow the
DPoPheader. It's a custom header, so the browser checks it in the preflight. If you list allowed headers explicitly, addDPoP.
Proving it works
Copy the access token from the Network tab and act as the attacker.
As a plain bearer token:
curl -i http://localhost:8081/api/orders \
-H "Authorization: Bearer $STOLEN_TOKEN"
With the DPoP scheme, no proof:
curl -i http://localhost:8081/api/orders \
-H "Authorization: DPoP $STOLEN_TOKEN"
With a captured proof, on another endpoint:
curl -i -X DELETE http://localhost:8081/api/orders/42 \
-H "Authorization: DPoP $STOLEN_TOKEN" \
-H "DPoP: $CAPTURED_PROOF"
All three must return 401:
- The token has a
cnfclaim, so it can't be downgraded to bearer. - DPoP scheme without a proof is incomplete.
- The proof's
htmandhtudon't match the request.
A 200 on any of them means something is misconfigured.
One more test: get a token without a proof (e.g. curl on the token endpoint) and call the API as bearer. If it works, DPoP is available but not required. See below.
Limits
It doesn't stop XSS. A script in your page can't extract the private key, but it can still send requests from the page. DPoP stops the token from working elsewhere. You still need a Content Security Policy and careful dependency management.
Replay protection is per instance. Spring Security tracks proof jtis in memory. With several API instances, a proof can be replayed on another one. The window is small (proofs expire after about 30 seconds), but it exists.
Lessons learned
The code is small. Understanding what each layer enforces is where the time goes.
Defaults change between versions
DPoP is on by default in Spring Security 6.5 and 7.0, opt-in in 7.1. Nothing warns you: the app starts, bearer tokens work, DPoP requests fail. For security features, read the source of the version you actually run.
Optional means absent
Every layer has an "if possible" mode:
- oidc-spa
autofalls back to bearer. - Keycloak, with the switch off, issues bearer tokens to clients without proofs.
- The API still accepts bearer tokens.
Fine for migration. But together, an attacker doesn't need to break DPoP, just find the path where it isn't required. Turn the fallbacks off: Keycloak switch on, oidc-spa enforced, and verify with the extra test.
The API must know its own URL
Spring Security compares htu with the request URL it sees. Behind a reverse proxy, the browser signs https://api.example.com/... while the app sees http://10.0.0.12:8080/..., and every proof fails with invalid_dpop_proof.
Fix it by honoring forwarded headers, but only from your trusted proxy. Otherwise clients can tell your API what its own URL is.
Clocks matter
Proofs are valid for seconds. A drifting laptop clock or a container without time sync produces correctly signed proofs that still get rejected. Check the clock before the code.
Takeaway
For every token in your system, ask: what does it prove, to whom, and what happens if it leaks? DPoP made me answer that question, and the system is stronger for it.
Try it
If your SPA already uses Keycloak, rollout takes four steps:
- Spring Boot: add
.dPoP(...)(7.1+) and allow theDPoPheader in CORS. Nothing breaks. - Angular: enable
DPoP({ mode: "auto" })and check the Network tab. - Test: the three replay requests return
401. - Enforce: turn on Require DPoP bound tokens in Keycloak and switch oidc-spa to
enforced.
Steps 1 to 3 are safe to ship one at a time. Step 4 is what actually protects your users.