Laravel/Passport 客户端授权令牌模式下如何获取当前令牌所属的client

Laravel10项目中使用了laravel/passport授权认证,配置正常后开始使用。

由于使用的是客户端授权令牌模式,因此,客户端请求/oauth/token,模拟如下:

use Illuminate\Support\Facades\Http;

$response = Http::asForm()->post('http://passport-app.test/oauth/token', [
    'grant_type' => 'client_credentials',
    'client_id' => 'client-id',
    'client_secret' => 'client-secret',
    'scope' => 'your-scope',
]);

return $response->json()['access_token'];

客户端拿到access_token后,使用Bearer token携带该access_token请求某个由client中间件值守的路由:

Route::get('/test', function (){
    $psr = (new PsrHttpFactory(
        new Psr17Factory,
        new Psr17Factory,
        new Psr17Factory,
        new Psr17Factory
    ))->createRequest(\request());
    $server = app()->make(ResourceServer::class);
    $psr = $server->validateAuthenticatedRequest($psr);
    $oauth_client_id = $psr->getAttribute('oauth_client_id');
    $client = Client::query()->find($oauth_client_id);
    dd($client);
})->middleware('client');

通过这种方法可以拿到客户端信息,但是总觉得是我不了解laravel/passport的功能,有没有更简单的办法?

正在努力学习的小逗比 [ dobeen.net ]
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
Mutoulee
最佳答案

已解决,GPT的解决方案: $oauth_client_id = $request->attributes->get('oauth_client_id');

11个月前 评论
琳琅天上 3个月前
讨论数量: 4
Mutoulee

已解决,GPT的解决方案: $oauth_client_id = $request->attributes->get('oauth_client_id');

11个月前 评论
琳琅天上 3个月前
sanders

我理解一下楼主的意思:

  1. 采用服务器间接口访问场景
  2. 服务端想获取 client_id

这样的话 request()->user()->token() 里面应该有你想要的 client_id

11个月前 评论
Mutoulee (楼主) 11个月前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!