【问题标题】:Laravel Oauth2 client authorizing and redirecting with GuzzleLaravel Oauth2 客户端使用 Guzzle 授权和重定向
【发布时间】:2015-06-09 02:52:53
【问题描述】:

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

如果我 print_r $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】:

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

    控制器:

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

    查看:

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

    我将重定向 uri/callback 返回到我的应用程序,然后使用 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. 使用 View 中的链接访问授权初始端点。
    2. 有一个 php 返回文件,该文件是获取必要令牌/访问凭据并存储到数据库然后返回到路由的请求的一部分。
    3. 路由运行一个控制器函数,该函数现在从您之前保存的数据库条目中获取数据,然后按照您的意愿进行操作。

    【讨论】:

    • 你能分享你的代码吗?我被困在同一个地方。我能够获得返回码,但是当我尝试执行下一步 POST 时,我得到了一个未经授权的用户
    猜你喜欢
    • 1970-01-01
    • 2020-07-16
    • 1970-01-01
    • 1970-01-01
    • 2017-09-05
    • 2020-03-27
    • 1970-01-01
    • 2013-09-05
    • 2019-01-09
    相关资源
    最近更新 更多