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 ]
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
Mutoulee
最佳答案

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

1年前 评论
琳琅天上 5个月前
讨论数量: 4
Mutoulee

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

1年前 评论
琳琅天上 5个月前
sanders

我理解一下楼主的意思:

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

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

1年前 评论
Mutoulee (楼主) 1年前

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