Implement proper token exchange, refresh, and validation using JWKS to support seamless and authenticated integrations.
To receive a new set of tokens, perform a token exchange through a POST
request to the token endpoint. Remember to always save the new refresh_token
in the database, since the old one will be invalid.
Access tokens are opaque - they are random strings that you cannot decode. Validation should only be performed on the id_token
. You do not have to validate the access token before using it.
const data = new URLSearchParams();
data.append("refresh_token", "<your refresh token>");
data.append("client_id", "<your client id>");
data.append("grant_type", "refresh_token");
fetch("https://login.klarna.com/eu/lp/idp/oauth2/token", {
method: "POST",
headers: {
At any point of time you can request the latest user data using the /userinfo endpoint. It requires a valid access_token as authorization and returns the same data structure as you can find in the id_token. Remember to get the fresh access_token, described in step 5. Integrate in purchase flow, using /userinfo. Using a new access_token
in the /userinfo
ensures you get the most up to date information we have for the customer without requiring them to re-login.
fetch("https://login.klarna.com/eu/lp/idp/userinfo", {
headers: {
Authorization: "Bearer <access token>",
}
})
Validate id_token
: validating an OAuth 2.0 token using a JWKS (JSON Web Key Set) endpoint, such as the one provided by Klarna, involves several steps. Here's an outline of how you might proceed:
Node sample implementation
const jwt = require('jsonwebtoken');
const jwkToPem = require('jwk-to-pem');
async function verifyTokenWithJWKS(token, jwksUri) {
try {
// Decode the token header without verification
const { header } = jwt.decode(token, { complete: true });
if (!header || !header.kid) {
throw new Error('Invalid token header');
}