如何使用Laravel Passport认证

607 阅读4分钟

开始使用Laravel Passport认证

现在的大多数系统都需要认证来访问资源。例如,用户登录或API资源访问。在本教程中,我们将讨论Laravel Passport包来验证你的应用程序API。该任务包括创建和验证令牌。

目标

在本教程结束时, 你应该能够创建你的Laravel应用API并使用Laravel passport包来保护它们.

先决条件

为了跟随这篇文章, 读者应该具备以下条件:

  • 在你的开发环境中安装Laravel 8应用程序.需要有Laravel的基本知识来跟随这篇文章.
  • Postman应用程序来测试我们的应用程序
  • RESTful APIs.你应该熟悉GET,PUT,POST,CREATE,DELETE 操作.

安装'passport'包

要安装这个包到你正在运行的应用程序,请运行以下命令。

cd api-authentication-app

composer require laravel/passport

输出。

 -------------------------------------------------------     
  - Installing league/event (2.2.0): Downloading (100%)         
  - Installing lcobucci/jwt (4.1.4): Downloading (100%)         
  - Installing league/oauth2-server (8.2.4): Downloading (100%)         
  - Installing firebase/php-jwt (v5.4.0): Downloading (100%)         
  - Installing laravel/passport (v10.1.3): Downloading (100%)   //passport downloaded
----------------------------------------------- # omitted installations

准备护照

Passport 自带的数据库设置,以存储其访问令牌和0Auth2客户端活动。因此,我们应该按照以下方式运行我们的迁移,以创建表。

php artisan migrate

输出。

# This command generates tables for passport auth plus default Laravel tables
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated:  2014_10_12_000000_create_users_table (99.77ms)
----------------------------------- # omitted tables
Migrating: 2016_06_01_000001_create_oauth_auth_codes_table
Migrated:  2016_06_01_000001_create_oauth_auth_codes_table (209.35ms)
Migrating: 2016_06_01_000002_create_oauth_access_tokens_table
Migrated:  2016_06_01_000002_create_oauth_access_tokens_table (227.16ms)
Migrating: 2016_06_01_000003_create_oauth_refresh_tokens_table
Migrated:  2016_06_01_000003_create_oauth_refresh_tokens_table (124.49ms)
Migrating: 2016_06_01_000004_create_oauth_clients_table
Migrated:  2016_06_01_000004_create_oauth_clients_table (115.61ms)
Migrating: 2016_06_01_000005_create_oauth_personal_access_clients_table
Migrated:  2016_06_01_000005_create_oauth_personal_access_clients_table (85.12ms)
---------------------------------------- # omitted tables

现在我们有了我们的passport 认证表,我们需要设置encryption keys ,我们将在应用程序中使用这些表来生成安全access tokens

php artisan passport:install

输出。

# this command generates the encryption keys, personal access client, and password
# grant client which we'll use to generate the access tokens
Encryption keys generated successfully.
Personal access client created successfully.
Client ID: 1
# your client id 1 will be different from the output below
Client secret: KTIqQ7nwiIoJf9uxxxxxxxxxxxxxxxxxxxxxxxx
Password grant client created successfully.
Client ID: 2
# your client id 2 will be different from the output below
Client secret: 43x92qhcW4Itxxxxxxxxxxxxxxxxxxxxxxxxx

设置模型以使用passport/Passport配置

我们在User 模型上进行这些配置,以帮助我们访问用户令牌。因此,我们将有能力对他们进行认证。

因此,我们将添加Laravel\Passport\HasApiTokens 特质到我们Laravel生成的用户模型(App/Models/User)。

<?php

namespace App\Models;

------------------------------------
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
    // our user table columns
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];
}

接下来, 更新App\Providers\AuthServiceProvider ,如下所示:

<?php

------------------------------------------
use Laravel\Passport\Passport;

class AuthServiceProvider extends ServiceProvider
{
    protected $policies = [
        'App\Models\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * we call the passport: routes 
     * to register routes that our application will use * to issue tokens and clients
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();
        // call passport:routes() here
        if (! $this->app->routesAreCached()) {
            Passport::routes();
        }
    }
}

现在我们已经有了一个注册tokens路线的方法, 让我们更新config/auth.php ,如下:

<?php

return [
----------------------------------------------------
/**
* update the guards api only
*/
    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        /**
        * update the driver from token to passport
        */
        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
            'hash' => false,
        ],
    ],
    -------------------------------------------------------

];

添加认证控制器

现在我们已经设置好了passport 的配置,让我们创建一个认证控制器。

php artisan make:controller passportAuthController

更新这个控制器,如下所示。

<?php
----------------------------------------
class passportAuthController extends Controller
{
    /**
     * handle user registration request
     */
    public function registerUserExample(Request $request){
        $this->validate($request,[
            'name'=>'required',
            'email'=>'required|email|unique:users',
            'password'=>'required|min:8',
        ]);
        $user= User::create([
            'name' =>$request->name,
            'email'=>$request->email,
            'password'=>bcrypt($request->password)
        ]);

        $access_token_example = $user->createToken('PassportExample@Section.io')->access_token;
        //return the access token we generated in the above step
        return response()->json(['token'=>$access_token_example],200);
    }

    /**
     * login user to our application
     */
    public function loginUserExample(Request $request){
        $login_credentials=[
            'email'=>$request->email,
            'password'=>$request->password,
        ];
        if(auth()->attempt($login_credentials)){
            //generate the token for the user
            $user_login_token= auth()->user()->createToken('PassportExample@Section.io')->accessToken;
            //now return this token on success login attempt
            return response()->json(['token' => $user_login_token], 200);
        }
        else{
            //wrong login credentials, return, user not authorised to our system, return error code 401
            return response()->json(['error' => 'UnAuthorised Access'], 401);
        }
    }

    /**
     * This method returns authenticated user details
     */
    public function authenticatedUserDetails(){
        //returns details
        return response()->json(['authenticated-user' => auth()->user()], 200);
    }
}

记得阅读上面的控制器注释来理解代码。

添加应用认证路线

随着控制器准备好处理Requests ,让我们添加路由来完成应用程序的设置。

//routes/api.php
Route::post('register',[passportAuthController::class,'registerUserExample']);
Route::post('login',[passportAuthController::class,'loginUserExample']);
//add this middleware to ensure that every request is authenticated
Route::middleware('auth:api')->group(function(){
    Route::get('user', [passportAuthController::class,'authenticatedUserDetails']);
});

测试我们的护照应用程序

通过运行以下命令来服务你的应用程序。

# sever starts on port 8000 by default
php artisan serve

现在,使用postman或任何其他工具来测试你的应用程序。

登录输出。

token

结论

在这个教程中, 我们讨论了Laravel passport包.我们已经看到我们如何在Laravel应用程序中配置这个包来生成API访问令牌。

我已经试图带你完成实现POSTGET 方法的每个过程,即用户认证的例子,你现在可以在此基础上使用Laravel passport来设计安全的应用程序。