简体   繁体   English

Laravel Passport 从承载令牌中获取客户端 ID

[英]Laravel Passport Get Client ID from Bearer Token

I've set up the laravel passport and created clients.我已经设置了 Laravel 护照并创建了客户端。 When clients make a post request to my application using it api, all they send is the bearer access token along with the post values.当客户端使用它的 api 向我的应用程序发出 post 请求时,他们发送的只是不记名访问令牌以及 post 值。

Is there any way I can get the client id of the consuming application when they submit the post request simply from the bearer token.当他们仅从承载令牌提交发布请求时,有什么方法可以获取消费应用程序的客户端 ID。

Or is it entirely safe for the consuming application to send their client id along with the post fields?或者,消费应用程序将其客户端 ID 与 post 字段一起发送是否完全安全?

我认为这就是我需要的:

$request->user()->token()->client

If you deal with the grant type client_credentials you might consider the following solution:如果您处理授权类型 client_credentials,您可能会考虑以下解决方案:

Route::get('/get-client-cred', function (Request $request) {
    $bearerToken = $request->bearerToken();

    $tokenId = (new \Lcobucci\JWT\Parser())->parse($bearerToken)->getHeader('jti');

    return \Laravel\Passport\Token::find($tokenId)->client;
})->middleware('client_credentials');

Instead, if you are dealing with a personal access token you can retrieve the client as following:相反,如果您正在处理个人访问令牌,您可以按如下方式检索客户端:

Route::middleware('auth:api')->get('/get-client', function (Request $request) {
    return $request->user()->token()->client;
});

If you have used passport you can get the user id from the Auth facade using api guard like this:如果您使用过passport ,则可以使用api guardAuth门面获取用户 ID,如下所示:

$user_id = Auth::guard('api')->id();

or get the user:或获取用户:

$user = Auth::guard('api')->user();

This is what finally worked for me with Laravel 8.这就是 Laravel 8 最终对我有用的方法。

Note that I plagerised the solution from @judge2020's answer on GitHub .请注意,我从GitHub 上@judge2020 的回答中窃取了解决方案。

use Laravel\Passport\Token;
use Lcobucci\JWT\Configuration; /* composer require lcobucci/jwt */

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

    $bearerToken = request()->bearerToken();
    $tokenId = Configuration::forUnsecuredSigner()->parser()->parse($bearerToken)->claims()->get('jti');
    $client = Token::find($tokenId)->client;
    
})->middleware('client');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM