我已经使用 Laravel Passport 文档 成功创建了 server.app 和 client.app 。一切都按预期工作。
client.app 路由:
Route::get('callback', function (Request $request) {
$http = new GuzzleHttp\Client;
$response = $http->post('http://server.app/oauth/token', [
'form_params' => [
'grant_type' => 'authorization_code',
'client_id' => 3,
'client_secret' => 'secret',
'redirect_uri' => 'http://client.app/callback',
'code' => $request->code
]
]);
return json_decode((string) $response->getBody(), true)['access_token'];
});
默认情况下,这条路线返回 access_token ,我可以用它做任何我想做的事情。
要求:
http://server.app/oauth/authorize?client_id=3&redirect_uri=http%3A%2F%2Fclient.app%2Fcallback&response_type=code&scope=
回报:
http://client.app/callback?code=access_token
问题:
如何使用 client.app 中给定的 access_token 向 server.app 发出正确的请求,以获取例如 用户电子邮件。
我应该使用: http://server.app/api/user
请求获取数据吗?如果是,我该怎么做?如果可能,请写一个代码。
感谢您的任何回答。
原文由 Tauras 发布,翻译遵循 CC BY-SA 4.0 许可协议
我一直在为这个问题发疯!在尝试访问诸如
/api/user
类的路线时,为什么它一直吐出愚蠢的Unauthenticated
错误,这简直是毫无意义。经过一番搜索(MUCH search),我终于找到了答案。如果你从 Laracasts 看到这个 fero,你就是我的英雄!https://laracasts.com/discuss/channels/laravel/laravel-53-passport-api-unauthenticated-in-postman-using-personal-access-tokens
编辑:
对上述
app\Providers\RouteServiceProvider.php
进行更改后,请继续执行以下示例。首先,我们需要检索一个新的
access_token
。为此,我使用 密码grant_type
(更多信息: https ://laravel.com/docs/5.4/passport#password-grant-tokens )为了检索新的
access_token
,我在routes/web.php
上创建了一条新路线,并将其命名为/connect
。然后,我将上面链接中的代码放入其中:使用 Chrome Postman ,您需要:
GET
Accept
和值application/json
示例结果:
突出显示
access_token
字符串并将其复制到文本编辑器。然后,您需要在
routes/api.php
中创建一个新路由。下面的路由将简单地输出当前 API 用户的信息:完成上述操作后,对 Postman 进行以下更改:
GET
Authorization
和值Bearer access_token_here
(将access_token_here
替换为您之前复制的访问令牌)示例输出: