如何使用客户端证书而不是秘密(PHP)让 OpenID Connect 工作?

问题描述 投票:0回答:1

我是 OIDC 的新手,正在部署 SSO 应用程序。使用带有以下代码的客户端密钥时一切正常,但我公司的 Azure AD/Entra 配置在使用移动设备时需要使用客户端证书(而不是密钥)。

我已使用 openssl 生成了密钥对并将公钥上传到 Azure 门户,确认指纹正确。但是我不知道如何将私钥输入到我的代码中。有人可以帮忙吗?

require_once 'vendor/autoload.php';

use Jumbojett\OpenIDConnectClient;
$oidc = new OpenIDConnectClient('*url*', '*clientid*', null);
$oidc->setTokenEndpointAuthMethodsSupported(['private_key_jwt']);
$oidc->authenticate();
print_r($oidc->requestUserInfo());
php azure-active-directory openid-connect
1个回答
0
投票

经过大量搜索和结合各种资源,我想我找到了答案。在这里发帖给可能有同样问题的其他人。

要点:

  1. 使用
    $oidc->setTokenEndpointAuthMethodsSupported()
  2. 启用“private_key_jwt”作为受支持的身份验证方法
  3. 编写一个自定义函数,使用由私钥签名的客户端信息创建标准 JWT。使用
    $oidc->setPrivateKeyJwtGenerator()
  4. 将其绑定到 $oidc
  5. Azure/OpenSSL 生成的公共证书指纹是一个十六进制字符串 - 需要将其转换为二进制,然后进行 Base64 编码,作为“x5t”参数添加到 JWT 标头:
    $headers['x5t'] = \base64_encode(\hex2bin('*public_key_thumbprint*'))

PHP OIDC 客户端代码:

require_once 'vendor/autoload.php';

use Jumbojett\OpenIDConnectClient;

$clientId = '*clientId*';
$oidc = new OpenIDConnectClient('*url*', $clientId, null);
$oidc->setTokenEndpointAuthMethodsSupported(['private_key_jwt']);
$oidc->setPrivateKeyJwtGenerator(function (string $token_endpoint) {
    global $clientId;
    $key = \file_get_contents('*private_key_file*');
    $headers = [
        'typ' => 'JWT',
        'alg' => 'RS256',
        'x5t' => \base64_encode(\hex2bin('*public_cert_thumbprint*')),
    ];
    $payload = [
        'iss' => $clientId,
        'sub' => $clientId,
        'aud' => $token_endpoint,
        'jti' => \base64_encode(\random_bytes(16)),
        'exp' => \time() + 300,
    ];
    openssl_sign(
        base64UrlEncode(json_encode($headers)) . "." . base64UrlEncode(json_encode($payload)),
        $signature,
        $key,
        "sha256WithRSAEncryption"
    );
    $jwt = base64UrlEncode(json_encode($headers)) . "." . base64UrlEncode(json_encode($payload)) . "." . base64UrlEncode($signature);

    return $jwt;
});
$oidc->authenticate();
print_r($oidc->requestUserInfo());

function base64UrlEncode(string $text): string
{
    return rtrim(strtr(base64_encode($text), '+/', '-_'), '=');
}
`
© www.soinside.com 2019 - 2024. All rights reserved.