JWT使用笔记

一、安装

1
composer require tymon/jwt-auth:dev-develop --prefer-source

二、发布配置文件

1
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"

三、生成秘钥

1
php artisan jwt:secret

四、更改UserModel

  1. 实现 Tymon\JWTAuth\Contracts\JWTSubject 接口
  2. 实现方法:getJWTIdentifier
  3. 实现方法:getJWTCustomClaims
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?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;

public function getJWTIdentifier()
{
return $this->getKey();
}

public function getJWTCustomClaims()
{
return [];
}
}

五、登录生成Token

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public function login(Request $request) {
$input = $request->only('mobile', 'password');
$jwt_token = null;

if (!$jwt_token = JWTAuth::attempt($input)) {
return response()->json([
'success' => false,
'message' => 'Invalid Email or password'
]);
}

return response()->json([
'success' => true,
'token' => $jwt_token
]);
}

六、根据token获取信息

1
2
3
4
5
6
public function getAuthUser(Request $request) {
$this->validate($request, ['token' => 'required']);
$token = $request->token;
$user = JWTAuth::setToken($token)->toUser();
return response()->json(['user'=>$user]);
}

七、注销

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public function logout(Request $request) {
$this->validate($request, ['token' => 'required']);
try {
JWTAuth::setToken($request->token)->invalidate();
return response()->json([
'code' => 200,
'message' => 'user logged out successfully'
]);
} catch (JWTException $exception) {
return response()->json([
'code' => 202,
'message' => 'Sorry, the user cannot be logged out:' . $exception->getMessage()
]);
}
}

八、备注

以上的说明中,用于授权的字段有两个,mobile和password,JWT对此并没有限制,用户可以自己定义,在生成TOKEN的时候,这些信息会被加入到最终生成的token中,当授权的时候,会解析这个token,将其中的字段提取出来,然后验证。因而,自己可以定义任何字段,只要确保对应的User模型有相应的字段。