php passport security,php – 使用Laravel Passport获取经过身份验证的用户并授予密码...

我用Laravel做了一个API REST,现在我正在尝试使用它.问题是我需要在API中验证用户,我使用的是Password Grant方法.我可以正确地验证用户,我可以获得访问令牌,但从那时起,我没有看到在我的消费应用程序中使用访问令牌检索经过身份验证的用户的方法.

我尝试使用这样的路由API:

Route::get('/user', function(Request $request) {

$user = $request->user();

// Even with

$user = Auth::user();

return $user;

});

没有骰子.我正在阅读Passport代码,但我无法弄明白.我的猜测是我需要指定一个新的防护类型或类似东西,因为Laravel Passport似乎没有提供这种类型的防护类型……

澄清事情:

>我有一个API REST应用程序,它是oAuth2服务器.

>我有另一个使用API​​ REST的应用程序.

>我确实知道工作流程.在我的情况下,使用密码授予,我在我的消费者应用程序中获取用户凭据,然后我向/ oauth / token发出请求,指定grant_type为密码,我提供用户凭据以及我的客户凭据,我相信他们用“php artisan passport:client –password”生成(注意–password选项)

>我可以毫无问题地获得访问令牌.我现在需要的是获取我刚刚从API REST验证的用户的JSON表示.但问题是:我只有一个访问令牌.我无法与用户联系.

或者我可以吗?也许我可以扩展验证密码授权请求的方法,以将生成的访问令牌与正在验证的用户相关联…… *灯泡打开*

消费应用测试代码:

try {

$client = new Client();

$result = $client->post('https://myapi.com/oauth/token', [

'form_params' => [

'grant_type' => 'password',

'client_id' => '5',

'client_secret' => 'my_secret',

'username' => 'user_I_am_authenticating',

'password' => 'the_user_password',

'scope' => '',

]

]);

$access_token = json_decode((string) $result->getBody(), true)['access_token'];

$result = $client->get('https://myapi.com/client/user', [

'headers' => [

'Content-Type' => 'application/json',

'Accept' => 'application/json',

'Authorization' => "Bearer $access_token",

]

]);

return (string) $result->getBody();

} catch (GuzzleException $e) {

return "Exception!: " . $e->getMessage();

}

请注意,https://myapi.com/client/user路由只是我在API中进行测试的路线.该路线定义为:

Route::get('/user', function(Request $request) {

return $request->user();

});

现在.我知道这不起作用.这就是我想要实现的目标.知道在给定access_token / bearer_token的情况下发出请求的用户.

谢谢.

解决方法:

你忘记了适当的中间件.

Route::get('/user', function(Request $request) {

return Auth::user();

})->middleware('auth:api');

如果不提及auth中间件,则不会触发身份验证流程.这就是你得到null的原因.

标签:laravel-5-4,php,oauth-2-0,laravel-passport

来源: https://codeday.me/bug/20191005/1856563.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值