Keycloak:使用 PHP 验证 access_token

Hai*_*uar 1 php jwt openid-connect keycloak

假设我通过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"
}
Run Code Online (Sandbox Code Playgroud)

有没有办法像https://jwt.io/那样使用 PHP解码 jwt 令牌的有效负载?谢谢。

Adi*_*dis 6

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

你为什么要解码access_token?通常它会id_token被解码,以便客户端可以验证最终用户的身份。解码过程需要 JWT 对其签名进行验证。

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

  1. 智威汤逊
  2. 密钥/公钥
  3. 用于编码 JWT 的算法

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

$decoded = JWT::decode($jwt, $key, array('HS256'));
Run Code Online (Sandbox Code Playgroud)

如果您想在不验证 JWT 签名 ( unsafe ) 的情况下解码 JWT,您可以创建一个函数来分隔 JWT 的每个部分:标头、正文和签名及其本身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]));
}
Run Code Online (Sandbox Code Playgroud)

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

$header = decodeJWT($id_token, 0);
Run Code Online (Sandbox Code Playgroud)

然后,您可以将标头传递给下面的函数以获取用于编码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);
Run Code Online (Sandbox Code Playgroud)

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

$decoded = JWT::decode($id_token, $key, array('RSA256'));
Run Code Online (Sandbox Code Playgroud)

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