FHIR上的史诗- PHP-JWT

bzzcjhmw  于 2022-12-21  发布在  PHP
关注(0)|答案(1)|浏览(117)

我正在尝试获取jwt令牌,但每次尝试时都出现错误。以下是我尝试过的方法。我确实在没有软件包的情况下获取了jwt令牌,但当我使用jwt.io检查签名验证时,它每次都失败。使用软件包,我会得到不同的错误,如 * 私钥无法加密 *,有时还有 * 无效算法 *。请纠正我哪里搞砸了。

*不使用php-Jwt

$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

1.安装了软件包 * 编写器需要firebase/php-jwt --ignore-platform-req=ext-mongodb*
1.已在我的控制器中使用所需文件

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

1.尝试的编码:

$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/上它显示为未经验证。

xnifntxz

xnifntxz1#

固定

  • 使用此函数代替hash_mac()
openssl_sign($data, $signature, $privateKey, OPENSSL_ALGO_SHA384);
  • 确保如果密钥存储在PHP变量中,则将密钥格式化为:
$privateKey =  "------BEGIN PRIVATE KEY------\n".
"MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC7VJTUt9Us8cKj\n".
"MzEfYyjiWA4R4/M2bS1GB4t7NXp98C3SC6dVMvDuictGeurT8jNbvJZHtCSuYEvu\n".
.
.
.
"TQrKhArgLXX4v3CddjfTRJkFWDbE/CkvKZNOrcf1nhaGCPspRJj2KUkj1Fhl9Cnc\n".
"dn/RsYEONbwQSjIfMPkvxF+8HQ==\n".
"------END PRIVATE KEY------";

双引号""将每一行括起来,并在每一行末尾加上\n

相关问题