laravel中使用jwt

Laravel框架
654
0
0
2022-04-11
标签   Laravel授权

安装使用jwt

1.下载laravel
composer create-project –prefer-dist laravel/laravel jwt 6.* (laravel版本号可写可不写)
2.安装jwt扩展包
composer require tymon/jwt-auth:dev-develop –prefer-source
3.发布资源(这条命令会在config中生成jwt.php配置文件)
php artisan vendor:publish –provider=”Tymon\JWTAuth\Providers\LaravelServiceProvider”
4.生成jwt秘钥
php artisan jwt:secret
5.注册中间件

在app/Http/Kernel.php文件中 $routeMiddleware中添加如下代码:

'auth.jwt' => \Tymon\JWTAuth\Http\Middleware\Authenticate::class,

在需要的路由加上 auth.jwt中间件就可以正常使用

6.在config/auth.php中
  'guards' => ['web' => ['driver' => 'session','provider' => 'users',],

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

注:这里可以不修改

不修改使用方法如下:

 use Tymon\JWTAuth\Facades\JWTAuth;

$input = $request->only('email', 'password');
JWTAuth::attempt($input)//加密  
JWTAuth::invalidate($request->token);//删除
JWTAuth::authenticate($request->token);//解密获取信息

修改之后使用方法如下(当然修改之后上面的方法还可以继续使用):

auth('api')->attempt($input);
auth('api')->invalidate($request->token);
auth('api')->authenticate($request->token);

修改jwt默认用户表

默认使用的是app\User.php(默认链接的是users表),模型内容如下:

<?php

namespace App;


use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

    protected $table  = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */ 
    protected $fillable = ['name', 'email', 'password',];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token',];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = ['email_verified_at' => 'datetime',];
    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */ 
    public function getJWTIdentifier(){
       return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims(){
        return [];
    }
}
修改成member表
1.创建member数据表和对应的模型文件,模型文件代码同上
2.修改config\auth中代码,如下:
    'guards' => ['web' => ['driver' => 'session','provider' => 'users',],

        'api' => ['driver' => 'jwt','provider' => 'member',//users修改成member'hash' => false,],],

    'providers' => ['users' => ['driver' => 'eloquent','model' => App\User::class,],//添加member代码'member' => ['driver' => 'eloquent','model' => App\Models\Member::class,],],