Laravel Oauth2 客户端使用 Guzzle 进行授权和重定向

问题描述 投票:0回答:1

我正在尝试使用 Laravel 和 Guzzle 的授权代码流来访问 REST API。

他们指定了要求:

GET https://api.restsite.com/oauth2/authorize ?
    client_id = [application id] &
    response_type = code &
    scope = orders inventory &
    redirect_uri = [redirect uri]

在 Laravel 中我是这样实现的:

// Create a client
$client = new Client();

    $request = $client->createRequest(
        'GET', 'https://api.restsite.com/oauth2/authorize',[
            'query' => [
                'client_id' => 'myclientid',
                'response_type' => 'code',
                'scope' => 'inventory',
                'redirect_uri' => 'https://myownsite/uri.php',
            ],
        ]
    );

    // Send the request
    $response = $client->send($request);

如果我打印 $response 它将显示他们网站的登录页面。

现在,他们的下一个指令是成功登录后,它将转到我的重定向 uri,如下所示:

https://[redirect uri]?code=[authorization code]

有了这个授权码,我现在可以按照他们的指示再次拨打电话:

POST https://api.restsite.com/oauth2/token ?
     grant_type = authorization_code &
     code = [authorization code] &
     redirect_uri = [redirect uri]

最后,如果一切顺利,JSON 响应应该如下所示:

{
  "access_token": [access token], 
  "token_type": "bearer", 
  "expires_in": 3600
}

我可以用它来访问另一个端点上的受保护资源。

现在我被困在 Laravel 中,在 Guzzle 第一次调用“授权”端点后,返回的 $response 我不知道该怎么处理它,因为我没有被自动重定向到任何地方。

所以我临时做的就是添加了这个返回视图:

return View::make('welcome')->with('response', $response);

这很好,一个花花公子(看起来很丑,没有CSS,因为实际上不是来自他们的网站),但当我查看源代码时,似乎有正确的形式代码。

当前的URL只是我的项目根目录:

http://myserver:8080/test/public/

但是,在我尝试登录后,我被重定向到服务器的主根文件夹:

http://myserver:8080/

我不确定如何让它至少正确加载重定向 URI,以便我可以采用该 URI ?code= 参数并使用它根据需要进行另一个调用。

我希望到目前为止我没有失去任何人。预先感谢!

php laravel oauth-2.0 laravel-5 guzzle
1个回答
0
投票

我所做的不是使用 Guzzle 处理来自外部站点的授权初始步骤,而是简单地执行了以下操作之一:

控制器:

return redirect::to('https://api.restsite.com/oauth2/authorize?');

查看:

<a href="https://api.restsite.com/oauth2/authorize?">Approve App</a>

我将重定向 uri/回调返回到我的应用程序,然后使用 Guzzle 发布和检索必要的令牌,这些令牌作为 json 响应返回,因此不需要任何更多的外部站点/重定向。

最终我可以使用实际的资源端点来查询数据。

更新

根据要求,我提供了有关该过程如何进行的更多详细信息:

查看(authtoken.blade.php):

<a href="https://api.restsite.com/oauth2/authorize?client_id=XXX&response_type=code&scope=inventory&redirect_uri=https://myownsite.com/return_uri.php&access_type=offline">Request New Token</a>

return_uri.php (http://myownsite.com/)

<?php

ob_start();
$url = 'http://myserver:8080/test/public/authtoken/get';

date_default_timezone_set('America/Los_Angeles');

$authcode = $_GET['code'];

echo 'Authorization code: ' . $authcode;
sleep(15);

$servername = "xx.xxx.xxx.xx";
$username = "user";
$password = "pass";
$dbname = "ca";
$now = date("Y-m-d H:i:s");

if ($authcode) {

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 

    $sql = "INSERT INTO credentials (id, auth, authDate)
    VALUES ('1','$authcode', '$now') ON DUPLICATE KEY UPDATE auth = values(auth), authDate = values(authDate) ";

    if ($conn->query($sql) === TRUE) {
        echo "Auth code created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

    $conn->close(); 

    //echo '<br><br><a href="http://myserver:8080/test/public/authtoken/get">go back</a>';

    while (ob_get_status()) 
    {
        ob_end_clean();
    }       

    header( "Location: $url" );

}

?>

控制器

public function authtokenget()
{

    $creds = Credentials::find(1);
    $auth = $creds->auth;

    $client = new Client();

    $client->setDefaultOption('verify', false); 

    $data = 'grant_type=authorization_code&code=$auth&redirect_uri=https://myownsite.com/return_uri.php';
    $data_string = json_encode($data);   
    $datlen = strlen($data_string);

    $request = $client->createRequest(
        'POST', 'https://api.restsite.com/oauth2/token',[
            'headers' => [
                'content-type' => 'application/x-www-form-urlencoded',
                'content-length' => $datlen,
            ],
            'body' => $data_string,
            'auth' => ['xxxxx=', 'xxxxx'],
        ]
    );

    $response = $client->send($request);

}

回顾

  1. 使用视图中的链接访问授权初始端点。
  2. 拥有一个 php 返回文件,该文件是请求的一部分,用于获取必要的令牌/访问凭据并存储到数据库,然后返回到路由。
  3. 该路由运行一个控制器函数,该函数现在从您之前保存的数据库条目中获取数据,以便现在按照您的意愿进行操作。
© www.soinside.com 2019 - 2024. All rights reserved.