Laravel9.x Rest Api passport验证

作者: 温新

分类: 【Laravel】

阅读: 2197

时间: 2022-07-09 12:59:25

hi,我是温新,一名PHPer

记录点滴

第一步:创建项目

composer create-project laravel/laravel la9-passport

第二步:配置数据库

.env 文件

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=database_user_name
DB_PASSWORD=database_password

第三步:安装 passport

安装 passport

composer require laravel/passport

执行迁移

php artisan migrate

生成客户端秘钥

php artisan passport:install

第四步:设置 passport 验证

1)模型中设置 passport HasApiTokens

// app/Models/User.php

<?php
namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
// use Laravel\Sanctum\HasApiTokens;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
	// 其他的省略
}

2)在 App\Providers\AuthServiceProvider.php 文件中注册 Passport::routes路由

<?php
// app/Providers/AuthServiceProvider.php
namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use Laravel\Passport\Passport;

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

    public function boot()
    {
        $this->registerPolicies();

        if (! $this->app->routesAreCached()) {
            Passport::routes();
        }
    }
}

3)config/auth.php 中配置 api 路由驱动

<?php
// config/auth.php 
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
],

第五步:创建 api 控制器和路由

1)api 控制器

php artisan make:controller Api/AuthController 

2)编写 AuthController.php

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Hash;

class AuthControler extends Controller
{
    public function login(Request $request)
    {
        if (auth()->attempt($request->all())) {
            return response([
                'user' => auth()->user(),
                'access_token' => auth()->user()->createToken('authToken')->accessToken,
            ], Response::HTTP_OK);
        }

        return response([
            'message' => 'This User does not exist'
        ], Response::HTTP_UNAUTHORIZED);
    }

    public function register(Request $request)
    {
        $user = User::create([
            'name'  =>  $request->name,
            'email' =>  $request->email,
            'password'  =>  Hash::make($request->password),
        ]);

        return response($user, Response::HTTP_CREATED);
    }
}

3)注册路由

// routes/api.php

Route::post('login', [\App\Http\Controllers\Api\AuthControler::class, 'login']);
Route::post('register', [\App\Http\Controllers\Api\AuthControler::class, 'register']);

第六步:api 测试

我通过 postman 来进行 api 路由测试。在路由测试中,需要添加相关头信息,下面一起来看看。

1)调用注册接口,路由:http://la9_passport.test/api/register

添加头信息:Accept:application/json; body 中添加 name email password字段相关值,调用成功后,返回值如下:

{
    "name": "test",
    "email": "test@qq.com",
    "updated_at": "2022-07-09T10:30:32.000000Z",
    "created_at": "2022-07-09T10:30:32.000000Z",
    "id": 1
}

2)调用登录接口,路由:http://la9_passport.test/api/login

添加头信息:Accept:application/json; body 中添加 email password字段相关值,调用成功后,返回值如下:

{
    "user": {
        "id": 1,
        "name": "test",
        "email": "test@qq.com",
        "email_verified_at": null,
        "created_at": "2022-07-09T10:30:32.000000Z",
        "updated_at": "2022-07-09T10:30:32.000000Z"
    },
    "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiNTFiMmM2YmZjNWFkN2VkMjllMTBiN2UxMWM0YzMzZDRhZWFmZjkyMzkyYjRiZThkZDJmZTZiZWVmNDc5YjM4MGJhNmIyYTdhYTRmMzFmY2QiLCJpYXQiOjE2NTczNjI5MzEuNDM5ODAzLCJuYmYiOjE2NTczNjI5MzEuNDM5ODA2LCJleHAiOjE2ODg4OTg5MzEuNDI4ODA2LCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.jsFDSGbn4bOykyVXUimfs_I2SBugmZT7Z9a1gO9Y4fkrct3G93qVX9vOvZ1HbTVPxOdspUgqYMPWp0z1qU8CFGD2v2h0QtVvVufijKekuKgAumi1H4aV3-B1jIF7EZZXFEUcqmdXOM-MzpmpjOfiWqrpnSKLt_X_R9ZCzIF7hryh2kFrT7hMEw_ZQmFFMbOBhjssOXQ6CsGyCtNQK9ilDVDWj6es9nY79QfWSDV5JpCbLGbPT5NkHcEnGGIdHhc9oNZVXK6mYqXiEX3U-fmLAFgzT-7uI1M6WmruSAk77H_QSrFoh6P2Aqz79D4TTgqFbqwQS9ugQ4PJ-zMMA__E47Yw7zHayHWdE0XJsHi5Uo65HwW2IWgf0alPUSbIlmRXYUQ7KX_1cm1A4YgdDx7hlQphZvZ9BCK4rpXETQzFg8ixBdg3G4vEaHn6S24K1oYYTpQblf0oAq0dYHwSexyn2fLtsWhwCWUfYJsjWVgTxAQ_7VHpMtDFd3Bk3c1Z9A6eDpfxxt6ePPCWlaJGDC1olNIME0nA0y0-7bvrPHmJC1v0wXYThwujXP05GGL8YmFIW7PVPkXIVFxOn1gy5KvbZk9hvuKoPLpiSdkdtL1RULSWmkyPHLhDwg78aHNz81Sl72KrsViKQZI6HUGjo1bQBcGI0sYiwR7v_mW0q1wZ1tM"
}

第七步:api 资源测试

上面的步骤中完成了 api 的登录认证并返回了用户的 access_token,以后用户获取其它资源都需要使用该 access_token 来获取,下面将演示获取用户资源。

1)创建控制器

php artisan make:controller Api/UserControler

2)编写控制器

// Api/UserController.php
<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;

class UserControler extends Controller
{
    public function index()
    {
        return User::all();
    }
}

3)创建路由

// routes/api.php

<?php
    
// 注意,该路由添加了用户 api 认证的中间件
Route::apiResource('users', \App\Http\Controllers\Api\UserControler::class)->middleware('auth:api');

4)路由测试,路由:http://la9_passport.test/api/users

添加头信息:Accept:application/jsonAuthorization:Bearer 你的access_token; 调用成功后,返回值如下:

[
    {
        "id": 1,
        "name": "test",
        "email": "test@qq.com",
        "email_verified_at": null,
        "created_at": "2022-07-09T10:30:32.000000Z",
        "updated_at": "2022-07-09T10:30:32.000000Z"
    }
]
请登录后再评论