Currently leveraging Zitadel as my Identity Provider, I have set up a project and an API with a key. I am now in the process of acquiring a M2M token using the “JWT bearer token with private key” method, recommended by Zitadel (click here). Utilizing the code snippet below with the openid-client
library:
/* tslint:disable:no-console */
import { exportJWK, importPKCS8, SignJWT } from 'jose';
import { Issuer } from 'openid-client';
import NodeRSA from 'node-rsa';
import fs from 'fs';
import path from 'path';
const getToken = async () => {
const clientId = '27700000000000000';
// Step 1: Discover the OpenID Connect provider's configuration
const oidcIssuer = await Issuer.discover('https://xxxxxx-xxxxxx.zitadel.cloud');
// Step 2: Create a JWK from the private key
const keyJson = JSON.parse(fs.readFileSync(path.join(__dirname, '27700000000000001.json'), 'utf8'));
const rsa = new NodeRSA(keyJson.key);
const key = await importPKCS8(rsa.exportKey('pkcs8-private-pem'), 'RSA256');
const jwk = await exportJWK(key);
// Step 3: Create a new client with the JWK
const client = new oidcIssuer.Client({
client_id: clientId,
token_endpoint_auth_method: 'private_key_jwt',
}, {
keys: [jwk]
}
);
// Step 4: Generate a JWT signed with the private key
const jwt = await new SignJWT({
iss: clientId,
sub: clientId,
aud: oidcIssuer.metadata.token_endpoint
})
.setIssuedAt()
.setExpirationTime('5m')
.setProtectedHeader({
alg: 'RS256',
kid: keyJson.keyId
})
.sign(key);
// Step 5: Exchange the JWT for an access token
const tokenSet = await client.grant({
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
}, {
clientAssertionPayload: {
client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
client_assertion: jwt
}
});
console.log('Access Token:', tokenSet.access_token);
};
getToken();
Everything progresses smoothly until step 5. However, upon execution, I encounter the following error:
OPError: invalid_request (assertion missing)
Despite providing the assertion in step 5, I cannot identify the missing element. What am I overlooking?