我正在尝试获取 jwt 令牌,但每次我尝试的所有操作都会出现错误。以下是我尝试过的事情。我确实在没有包的情况下获得了 jwt-token,但是当我使用 jwt.io 检查签名验证时,每次都会失败。使用该软件包时,我遇到了不同的错误,例如私钥无法强制执行,有时算法无效。请纠正我哪里搞砸了。
$header = [
'alg' => "RS384",
'typ' => "JWT"
];
$payload = [
'iss' => 'my-client-id',
'sub' => 'my-client-id',
'aud' => "https://fhir.epic.com/interconnect-fhir-oauth/oauth2/token",
'jti' => (string)strtotime(gmdate("Y-m-d H:i:s")),
'exp' => strtotime(gmdate("Y-m-d H:i:s")) + 270,
];
$privateKey = "my private Key"
$headers_encoded = $this->base64url_encode(json_encode($header));
$payload_encoded = $this->base64url_encode(json_encode($payload));
$signature = hash_hmac('sha384', $headers_encoded.'.'.$payload_encoded, $privateKey, true);
// Encode the signature as a base64url string
$signature_encoded = $this->base64url_encode($signature);
$jwt = $headers_encoded.'.'.$payload_encoded.'.'.$signature_encoded;
- 使用 php-jwt
use Firebase\JWT\JWT; use Firebase\JWT\Key;
$check = JWT::encode(
$header,
$payload,
$privateKey,
'RS384'
);
我收到不同的错误,例如无法强制执行私钥,有时算法无效。请纠正我哪里搞砸了。
简单来说,这就是我正在做或正在尝试做的事情。我的代码的通用形式:
<?php
// Load the private key from a file
$privateKey = file_get_contents('private.key');
// Set the header and payload for the JWT
$header = [
'alg' => 'RS384',
'typ' => 'JWT'
];
$payload = [
'sub' => '1234567890',
'name' => 'John Doe',
'iat' => 1516239022
];
// Encode the header and payload as JSON strings
$headerEncoded = base64_encode(json_encode($header));
$payloadEncoded = base64_encode(json_encode($payload));
// Concatenate the header, payload, and secret to create the signature
$signature = hash_hmac('sha384', "$headerEncoded.$payloadEncoded", $privateKey, true);
// Encode the signature as a base64 string
$signatureEncoded = base64_encode($signature);
// Concatenate the header, payload, and signature to create the JWT
$jwt = "$headerEncoded.$payloadEncoded.$signatureEncoded";
echo $jwt;
我确实得到了 jwt 签名,但在 https://jwt.io/ 上它显示未经验证。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
已修复
将每一行用双引号
""括起来,并在每行末尾添加\n。