laravel中使用jwt

安装使用jwt

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

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

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

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

6.在config/auth.php中
1
2
3
4
5
6
7
8
9
10
11
12
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],

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

注:这里可以不修改

不修改使用方法如下:

1
2
3
4
5
6
 use Tymon\JWTAuth\Facades\JWTAuth;

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

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

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

修改jwt默认用户表

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?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中代码,如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  '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,
],
],