Laravel开发实践程序员Laravel

laravel 5.6 集成 passport 填坑

2018-04-26  本文已影响285人  HaRun

按照官方文档配置和安装好passport,文档在这里 https://laravel.com/docs/5.6/passport,中文文档看这里 http://laravelacademy.org/post/8909.html,当然与官方有一点区别,仔细看就会发现。

前提已经使用laravel开箱即用的auth

php artisan make:auth

重要:

$ php artisan passport:client

 Which user ID should the client be assigned to?:
 > 12

 What should we name the client?:
 > testwwww

 Where should we redirect the request after authorization? [http://localhost/auth/callback]:
 > http://127.0.0.1:8000/callback // 重要

New client created successfully.
Client ID: 12
Client secret: xxxxxxxx

这样地址就会重定向到

http://127.0.0.1:8000/callback

在/routes/api.php中添加

Route::get('/redirect', function (){
    $query = http_build_query([
        'client_id' => '12',
        'redirect_uri' => 'http://127.0.0.1:8000/callback',
        'response_type' => 'code',
        'scope' => '',
    ]);

    return redirect('http://127.0.0.1:8000/oauth/authorize?' . $query);
});

我没有配置 Frontend Quickstart ,直接跳到 Converting Authorization Codes To Access Tokens

官方配置,添加代码到:/routes/web.php

Route::get('/callback', function (Request $request) {
    $http = new GuzzleHttp\Client;

    $response = $http->post('http://your-app.com/oauth/token', [
        'form_params' => [
            'grant_type' => 'authorization_code',
            'client_id' => 'client-id',
            'client_secret' => 'client-secret',
            'redirect_uri' => 'http://example.com/callback',
            'code' => $request->code,
        ],
    ]);

    return json_decode((string) $response->getBody(), true);
});

注意:要在/routes/web.php和/routes/api.php文件使用:

use Illuminate\Http\Request;

当我按照上面配置测试时发现网页一直加载,很久都没有反应,这时需要强制关闭php连接服务,

mac 系统使用以下命令

mac 端口占用,我使用的是官方网页服务命令启动的(php artisan serve),会使用8000端口。
sudo lsof -i tcp:8000
kill pid xxx

杀掉这个进程后再次启动php连接服务,php artisan serve

这次我们修改一下官方代码

Route::get('/callback', function (Request $request) {
    print_r($request->code);
    exit;
});

如果没有授权将显示授权页面,完成授权后将直接打印code,复制code,然后在postman或者其他的api调试工具测试获取token
参数就是官方设置的那些参数,

            'grant_type' => 'authorization_code',
            'client_id' => '12',  // your client id
            'client_secret' => 'xxxxxxxxxxxxxxx',   // your client secret
            'redirect_uri' => 'http://127.0.0.1:8000/callback',
            'code' => copied code

这时就会获取到授权码token了

{
"token_type":"Bearer",
"expires_in":1296000,
"access_token":"xxxxxx",
"refresh_token":"xxxxxxx"
}

使用刚刚获取到的access_token,在postmen api调试工具测试获取用户信息

url

http://127.0.0.1:8000/api/user

header

undefinedaccept: application/json
accept-encoding: gzip, deflate
accept-language: en-US,en;q=0.8
content-type: application/x-www-form-urlencoded
user-agent: Mozilla/5.0 advanced-rest-client/ Safari/537.36
Authorization: Bearer xxxx

获取结果:

{
"id": 1,
"name": "xxx",
"email": "xxx@xxx.com",
"created_at": "2018-04-25 13:55:30",
"updated_at": "2018-04-25 13:55:30"
}

填坑完成,不知是什么原因导致网页不断加载的情况,如果哪位大侠知道,烦请给我留言,谢谢!

上一篇 下一篇

猜你喜欢

热点阅读