如何获得带有签名为JWT的私钥的访问令牌

时间:2020-10-21 10:18:05

标签: node.js keycloak openid-connect

我想从Keycloak服务器获取访问令牌。客户端(在Keycloak中)被配置为具有公钥和私钥的签名JWT,并且访问令牌将用于服务器到服务器的通信,因此没有用户直接参与。就我所知,此用例的授予类型是“ client_credentials”,而auth方法是“ private_key_jwt”。我尝试使用服务器NPM模块来执行此操作,而openid-client似乎是最有前途的。但是我无法正常工作。

问题是此库希望私钥不是作为签名的JWT,而是作为JWK集。我为此使用了jose模块,但是类型略有不兼容,因此无法正常工作:

import { Issuer } from 'openid-client';
import { JWK } from 'jose';

public getToken(privateKey) {
    const key = JWK.asKey(privateKey);

    Issuer.discover(
        'https://keycloak.domain/auth/realms/realm-name'
    ).then(
        (issuer) => {
            const client = new issuer.Client(
                {
                    client_id: '<client-id>',
                    token_endpoint_auth_method: 'private_key_jwt',
                },
                {
                    keys: [key], // <-- types incompatible
                }
            );
             client
                .grant({ grant_type: 'client_credentials' })
                .then(token => {
                    console.log('token', token);
                }
            );
        }
    );
)

我该如何解决?还是有另一个NPM模块更适合此用例?

1 个答案:

答案 0 :(得分:0)

解决方案是将密钥转换为纯JavaScript JWK格式的对象:

const key = JWK.asKey(jwk).toJWK(true);