HMRC使用PHP CURL请求OAuth 2.0授权代码

时间:2018-12-11 14:19:56

标签: php curl oauth

我正在尝试从HMRC(UK IRS)请求带有PHP CURL的OAuth 2.0授权代码。

HMRC的JAVA演示如下:

替换为应用程序的client_id和client_secret

String clientId = "YOUR-CLIENT-ID";
String clientSecret = "YOUR-CLIENT-SECRET";
String scope = "hello";
String redirectUri = "https://www.example.com/redirect";

构造OAuth 2.0授权请求

OAuthClientRequest request = OAuthClientRequest

.authorizationLocation("https://testapi.service.hmrc.gov.uk/oauth/authorize")
  .setResponseType("code")
  .setClientId(clientId)
  .setScope(scope)
  .setRedirectURI(redirectUri)
  .buildQueryMessage();

重定向到给定位置

httpServletResponse.sendRedirect(request.getLocationUri());

我编写的PHP CURL代码是:

<?php

$clientID = 'xxxx';
$scope='scope_1+scope_2+scope_3';
$redirectUri = 'https://xxxx/auth-redirect/';
$ResponseType='code';
$authLocation='https://test-api.service.hmrc.gov.uk/oauth/authorize';
$token = uniqid();
$server_token='xxxxx';

$headers = array(
    'Content-Type: application/x-www-form-urlencoded',
    'Accept: application/vnd.hmrc.1.0+json',
    'Authorization: Bearer ' . $server_token,
    );

//construct the OAuth 2.0 Authorize request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $authLocation);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "client_id=$clientID&scope=$scope&state=$token&redirect_uri=$redirectUri");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close ($ch);

echo $result; 

// Redirect the user to HMRC authorization page

/*
  header('Location: ' . $redirectUri . '?' . $location);
*/
?>

echo $ result给出“在标头中找不到CSRF令牌”。

HMRC网站上没有有关CSRF令牌的文档。我的代码是否存在一般问题,可能导致此错误?特别是,我不确定“ CURLOPT_POSTFIELDS”语法是否正确,或者该子句中包含的某些字段是否应包含在$ headers定义中。据我了解,我已经在php.net处检查了_POSTFIELDS,看来还可以。

0 个答案:

没有答案