当前位置: 首页 > 工具软件 > jwt-auth > 使用案例 >

laravel整合 tymon/jwt-auth

宗政金鹏
2023-12-01

安装 

composer require tymon/jwt-auth

#生成 JWT_SECRET 写入.env(自动写入)
php artisan jwt:secret

配置文件 config/app.php

//'providers'数组中添加如下代码
'providers'=>[
    ...
    Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
],


//在'aliases'数组中给 JWT 以下两个类添加别名方便之后生成 token 时使用,(当然也可以使用 Auth 门面生成 token , 所以不添加也是可以的。) 
	
'aliases' => [
    ...
    'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
    'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class,

 JWT 的配置文件


发布配置文件


#生成 JWT 的 jwt.php 配置文件 实际是 vendor/tymon/jwt-auth/config/config.php 这个文件copy
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"  

修改配置文件

//把 jwt.php 的 'providers'数组中的 token 生成类(Lcobucci)修改为 Namshi 代码如下:

'providers' => [
    //'jwt' => Tymon\JWTAuth\Providers\JWT\Lcobucci::class, // 使用 attempt() 方法生成 token
    'jwt' => Tymon\JWTAuth\Providers\JWT\Namshi::class, //使用 formUser() 方法生成 token

修改 config/auth.php 配置文件

//把 'defaults' 数组中的默认守卫改为'api'
 'defaults' => [
//        'guard' => 'web',
        'guard' => 'api',
        'passwords' => 'users',
    ],


//把'guards' 数组中的 api 守卫的驱动改为'jwt'
'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
//            'driver' => 'token',
            'driver' => 'jwt',
            'provider' => 'users',
            'hash' => false,
        ],
    ],

修改 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 Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
    use HasFactory, Notifiable;


 //实现 JWTSubject接口  两个函数
    public function getJWTIdentifier(){
        return $this->getKey();
    }

    public function getJWTCustomClaims(){
        return [];
    }

}

 

 类似资料: