首页 > 解决方案 > Laravel Passport -> 微服务用户认证

问题描述

对于一个应用程序,我制作了一堆微服务和一个网关。网关接收请求并从 giroservices 收集数据。一切正常。

网关接受所有请求并使用 Laravel Passport 对其进行身份验证。所以网关安装了 Laravel Passport。

[gateway]/users/login accepts the login parameters: 
[users]/users/verify login details and returns user object. All works fine. 

用户控制器.php

public function login(Request $request){

        $rules = [
            'email'     => 'required|email:rfc',
            'password'  => 'required|min:8',
        ];

        $user = $this->userService->verifyUser(['email'=> $request->email, 'password'=> $request->password]);


        return $this->successResponse(['token'=>$token], Response::HTTP_OK);
    }

具有完整的$user用户 json,包括 UUID。我想附上那个 UUID Laravel Passports OAuth。这样当用户进行身份验证时,我可以抽象出用户 UUID 并将其用于下一个请求。

{"data":{"uuid":"94b55bed-f084-468a-a2a7-51d38e96aed3","first_name":"John","last_name":"Due","locale":"en","email":"JohnDoe@mail.com","created_at":"2020-12-10T09:40:46.000000Z","updated_at":"2020-12-10T09:40:46.000000Z"}}

显然我理解 json_decode 这个,但是如何在 Laravel Passport 中手动创建访问令牌。我该怎么做?

标签: phplaraveloauth

解决方案


You can create an access token using a password grant client_id and client_secret along with the user credentials. You can do this using the /oauth/token route in the service that is holding the passport logic.

Here from the documentation

Creating A Password Grant Client
Before your application can issue tokens via the password grant, you will need to create a password grant client. You may do this using the passport:client Artisan command with the --password option. If you have already run the passport:install command, you do not need to run this command:

php artisan passport:client --password
Requesting Tokens
Once you have created a password grant client, you may request an access token by issuing a POST request to the /oauth/token route with the user's email address and password. Remember, this route is already registered by the Passport::routes method so there is no need to define it manually. If the request is successful, you will receive an access_token and refresh_token in the JSON response from the server:

use Illuminate\Support\Facades\Http;

$response = Http::asForm()->post('http://passport-app.com/oauth/token', [
    'grant_type' => 'password',
    'client_id' => 'client-id',
    'client_secret' => 'client-secret',
    'username' => 'taylor@laravel.com',
    'password' => 'my-password',
    'scope' => '',
]);

return $response->json();

which can be found here.

https://laravel.com/docs/8.x/passport#creating-a-password-grant-client


推荐阅读