Keycloak:使用 PHP 验证 access_token

Keycloak : validating access_token using PHP

假设我在通过 openid-connect

成功登录后收到令牌

http://xxxxxx/auth/realms/demo/protocol/openid-connect/token

{
    "access_token": "xxxxxx",
    "expires_in": 600,
    "refresh_expires_in": 1800,
    "refresh_token": "xxxxxx",
    "token_type": "bearer",
    "not-before-policy": xxxx,
    "session_state": "xxxxx",
    "scope": "email profile"
}

是否有任何方法可以像 https://jwt.io/ 那样使用 PHP 解码 jwt 令牌的有效负载?谢谢。

您可以使用这个库 https://github.com/firebase/php-jwt

为什么要解码 access_token?通常是 id_token 被解码,以便客户端可以验证 end-user 的身份。解码过程需要 JWT 对其签名进行验证。

你可以使用我上面提到的库。步骤很简单。您需要:

  1. JWT
  2. 密钥/Public密钥
  3. 用于对 JWT 进行编码的算法

以下代码段用于解码 + 验证 JWT。它使用 HS256,因此客户端必须拥有密钥:

$decoded = JWT::decode($jwt, $key, array('HS256'));

如果您想在不验证其签名的情况下解码 JWT(不安全),您可以创建一个函数来分隔每个 JWT 部分:header、body,还有签名,还有base64url decode呢。像这样:

// Pass in the JWT, and choose which section. header = 0; body = 1; signature = 2
public function decodeJWT($jwt, $section = 0) {

    $parts = explode(".", $jwt);
    return json_decode(base64url_decode($parts[$section]));
}

EDIT 如果你正在解码 + 验证使用非对称算法的 id_token 例如RSA256、RSA384 等,您需要 public 密钥。 OpenID Connect 定义了一个 JWK 集端点 (/.well-known/jwks.json),它以 JWK 格式列出了 public 键。您可以点击该端点并将响应保存在数组中。为了找到使用了哪个 public 密钥,JWK 有一个 kid 声明/ 属性。其中代表key id,public键的标识符。您可以解码 id_token 并使用 :

获取其 header
$header = decodeJWT($id_token, 0);

然后您可以将 header 传递给下面的函数以获取用于对 id_token 进行编码的密钥。参数 $keys 持有 JWK 设置响应:

function getIdTokenKey($keys, $header) {
    foreach ($keys as $key) {
        if ($key->kty == 'RSA') {
            if (!isset($header->kid) || $key->kid == $header->kid) {
                return $key;
            }
        }
    }   
    
    throw new Exception("key not found");
}

$key = getIdTokenKey($keys, $header);

最后调用 decode 函数,假设它使用 RSA256:

$decoded = JWT::decode($id_token, $key, array('RSA256'));

Edit(2) 另一方面,解码任何 JWT 的过程都是相同的,无论是访问令牌、ID 令牌还是传递给不同实体的任意数据服务器环境。