1

我正在尝试从 Salesforce 获取 JWT 不记名令牌。我正在尝试遵循他们的文档,但没有成功。 https://help.salesforce.com/articleView?id=remoteaccess_oauth_jwt_flow.htm&type=5

我得到的回报是 {"error":"invalid_grant","error_description":"invalid assertion"}

这是我的代码,不确定这有什么问题。需要帮助以尝试返回不记名令牌。

谢谢您,感谢您的帮助。

<?php

/**
 * Encode data to Base64URL
 * @param string $data
 * @return boolean|string
 */
function base64url_encode($data)
{
    return strtr(base64_encode($data), '+/', '-_');
}

define('CONSUMER_KEY', 'abc123');
define('CONSUMER_SECRET', 'abc123secret');
define('LOGIN_BASE_URL', 'https://login.salesforce.com');

//Json Header
$headerArray = array(
    "alg" => "RS256"
);

$jsonHeader = json_encode(($headerArray));
$header = base64url_encode($jsonHeader);

//Create JSon Claim/Payload
$expiration = strval(time() + (5 * 60));

$claimSet = array(
    "iss" => CONSUMER_KEY,
    "sub" => "test@email.com",
    "aud" => LOGIN_BASE_URL,
    "exp" => $expiration
);
$jsonClaimSet = (json_encode($claimSet));
$payload = base64url_encode($jsonClaimSet);

$encoded_JWT = $header . '.' . $payload;

// LOAD YOUR PRIVATE KEY FROM A FILE - BE CAREFUL TO PROTECT IT USING
$private_key = <<<EOD
-----BEGIN RSA PRIVATE KEY-----
testtesttesttest
-----END RSA PRIVATE KEY-----
EOD;

// This is where openssl_sign will put the signature
$signature = "";
// SHA256 in this context is actually RSA with SHA256
$algo = "SHA256";
// Sign the header and payload
openssl_sign($encoded_JWT, $signature, $private_key, $algo);


// Base64 encode the result
$secret = base64url_encode($signature);

$token = $header . '.' . $payload . '.' . $secret;

$token_url =  LOGIN_BASE_URL.'/services/oauth2/token';

$post_fields = array(
    'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
    'assertion' => $token
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $token_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
// curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type : application/x-www-form-urlencoded"));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);

$token_request_body = curl_exec($ch)
or die("Call to get token from code failed: '$token_url' - ".print_r($post_fields, true));

print_r($token_request_body);
?>
4

0 回答 0