为什么Client Creadentials应与Laravel Passport中的用户相关联?

Mee*_*ons 13 php oauth-2.0 laravel laravel-5 laravel-passport

我想使用Client Credentials来验证客户端应用程序以访问API.

我的问题是创建客户端凭据.使用php artisan passport:client要求我输入user_id以将客户端关联到该用户.我不明白.为什么客户端应用程序必须与用户关联?!或者还有另一种方式吗?

passport:client命令仅支持创建密码授予客户端和个人授权客户端.我不认为他们中的任何一个是我需要的.

我真正需要的是创建客户端凭据,仅客户端应用程序使用它来授权自己访问某些API.怎么做?

Ral*_*o94 7

我假设你想使用机器到机器的身份验证(没有用户交互)

我建议多次阅读文档来了解它.

我不相信有一个特定的方法来创建一个唯一的客户端凭据客户端,我所做的是创建一个个人客户端然后更改数据库中的个人客户端字段personal_access_client 1=>0

您可以使用个人客户端选项,如--help选项中所示

Usage:
  passport:client [options]

Options:
      --personal        Create a personal access token client
      --password        Create a password grant client
      --name[=NAME]     The name of the client
  -h, --help            Display this help message
...
Run Code Online (Sandbox Code Playgroud)

php artisan passport:client --personal

产量

Personal access client created successfully.
Client ID: 1
Client Secret: LbjQNxK5SQZ3pPrEBUwbkE8vaRkg8jh25Qh43HYy
Run Code Online (Sandbox Code Playgroud)

您需要使用除默认值之外的其他中间件,因为使用此方法时没有用户

  • 在内核中定义客户端凭证别名中间件
  • 添加中间件以进行路由
  • 发送请求

将客户端凭据中间件定义到http内核

课程\App\Http\Kernel:

 protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'client_credentials' => \Laravel\Passport\Http\Middleware\CheckClientCredentials::class,
        //ommited
    ];
Run Code Online (Sandbox Code Playgroud)

在路线上定义中间件

Route::get('/test', 'ApiTestController@test')->middleware('client_credentials');
Run Code Online (Sandbox Code Playgroud)

课程\App\Http\Controllers\ApiTestController:

public function test() {
        return response()->json(['data' => 'hey'] );
}
Run Code Online (Sandbox Code Playgroud)

php artisan route:list

GET|HEAD  | api/test | App\Http\Controllers\ApiTestController@test   | api,client_credentials  |
Run Code Online (Sandbox Code Playgroud)

发送请求

遵循client-credentials-grant-tokens文档中的指定请求

我使用Postman来简化,轻松发送Postman的测试请求(www.getpostman.com)

将授权设置为OAuth 2.0,图像:邮递员身份验证

将访问令牌URL,客户端ID,客户端密钥和授权类型设置为"客户端凭据",图像:邮递员OAuth字段

Postman创建一个令牌并将其附加到URL或Header,在本例中为header

Accept:application/json
Authorization:Bearer eyJ0eXAiOi...KCjK0
Run Code Online (Sandbox Code Playgroud)

响应:

{
  "data": "hey"
}
Run Code Online (Sandbox Code Playgroud)


小智 5

这些答案有点旧了。

您当然可以添加客户端凭据。

php artisan passport:client --client

protected $signature = 'passport:client
        {--personal : Create a personal access token client}
        {--password : Create a password grant client}
        {--client : Create a client credentials grant client}
        {--name= : The name of the client}
        {--provider= : The name of the user provider}
        {--redirect_uri= : The URI to redirect to after authorization }
        {--user_id= : The user ID the client should be assigned to }
        {--public : Create a public client (Auth code grant type only) }';
Run Code Online (Sandbox Code Playgroud)