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


Laravel Oauth2 client authorizing and redirecting with Guzzle

我正在尝试使用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);

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

现在,他们的下一条指令是在成功登录后,它将转到我的重定向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=参数,并根据需要使用它进行另一次调用。

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

我所做的不是使用Guzzle来处理来自外部站点的授权初始步骤,而是简单地做了其中一个:

控制器:

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

视图:

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

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

最后,在完成所有这些之后,我可以使用实际的资源端点来查询数据。

更新

根据请求,我提供了关于流程如何进行的更多细节:

视图(authtokenblade.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);
}

RECAP

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