首页 > 解决方案 > 使用 Guzzle 客户端的 Laravel OAuth 2.0 身份验证

问题描述

我正在 Laravel 中开发类似 Postman Client 的应用程序。为此,我正在使用 Guzzle 客户端。

对于 OAuth 2.0 身份验证,我使用以下链接作为参考,

参考链接

我试过下面的代码,

$token_storage = new FileTokenPersistence('/tmp/token.txt');

$baseurl="https://api.tradegecko.com/oauth/token";
$auth_code="";
$client_id="MYCLIENTID";
$client_secret="MYSECRET";
$redirect_uri="http://localhost:81/postman/public/request/instantadd";

if ($token_storage->hasToken() === false) {
    $auth_url = 'https://api.tradegecko.com/oauth/authorize?'.http_build_query([
        'client_id' => $client_id,
        'redirect_uri' => $redirect_uri,
        'response_type' => 'code',
        'prompt' => 'select_account',
        'scope' => '',
        'access_type' => 'offline',
    ]);

    echo "Go to the following link in your browser:\n\n";
    echo "    $auth_url\n\n";
    // if(! defined('STDIN')) define('STDIN', fopen("php://stdin","r"));
    echo "Enter verification code: ";
    $auth_code = trim(fgets(STDIN, 1024));
}


$reauth_client = new \GuzzleHttp\Client(['verify' => 'E:\cacert.pem',
    'base_uri' => $baseurl,
 ]);

$reauth_config = [
    'code' => $auth_code,
    'client_id' => $client_id,
    'client_secret' => $client_secret,
    'redirect_uri' => $redirect_uri,
];

$grant_type = new AuthorizationCode($reauth_client, $reauth_config);
$refresh_grant_type = new RefreshToken($reauth_client, $reauth_config);
$oauth = new OAuth2Middleware($grant_type, $refresh_grant_type);
$oauth->setTokenPersistence($token_storage);
$stack = HandlerStack::create();
$stack->push($oauth);

$client = new \GuzzleHttp\Client(['verify' => 'E:\cacert.pem',
    'handler' => $stack,
    'auth'    => 'oauth',
 ]);

$response = $client->get($requesturl, $options);
$result=json_decode($response->getBody(),true);

我在检索身份验证代码时遇到错误。当我转到 authurl 链接时,我得到了令牌。

我得到的错误是:

"message": "Unable to request a new access token"

另外,我不知道STDIN有什么用.....我怎么把auth代码放在这里?

请帮我。

问候,
雷哈

标签: phplaraveloauth-2.0postman

解决方案


推荐阅读