一、生成token
准备工作:
1、在控制器里引入 Tymon\JWTAuth\Facades\JWTAuth;
2、修改指定模型,我的是默认模型APP\User.php;
<?php
namespace App;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements JWTSubject
{
use Notifiable;
protected $table = 'test';
// Rest omitted for brevity
/**
* 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 [];
}
}
默认操作的表为users,指定自己的用户表,我的是test表
protected $table = 'test';
方法:
1、使用JWTAuth::attempt():
$param = array(
'email'=>123456789
'password'=>''
);
return JWTAuth::attempt($param);
方法会根据你指定定义的模型里面的定义的表进行查询,字段需要对应,密码需要根据要求加密,不然不会生成token
2、使用JWTAuth::fromUser();
$user = User::first();
return JWTAuth::fromUser($user);
需要使用模型层来获取用户实例,使用DB查询不符合方法需要的数据
二、验证token
1、验证
在中间件里验证对token进行验证,在App\Http\Kernel.php里面的路由中间件里添加
protected $routeMiddleware = [
........
'jwt.api.auth' => \App\Http\Middleware\CheckToken::class,
]
在App\Http\Middleware里面添加中间件文件,我的文件名字是checktoken.php
<?php
namespace App\Http\Middleware;
use Closure;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
class CheckToken
{
/**
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
try {
if (! $user = JWTAuth::parseToken()->authenticate()) { //获取到用户数据,并赋值给$user
return response()->json([
'errcode' => 1004,
'errmsg' => 'user not found'
], 404);
}
//如果想向控制器里传入用户信息,将数据添加到$request里面
$request->attributes->add($userInfo);//添加参数
return $next($request);
} catch (TokenExpiredException $e) {
return response()->json([
'errcode' => 1003,
'errmsg' => 'token 过期' , //token已过期
]);
} catch (TokenInvalidException $e) {
return response()->json([
'errcode' => 1002,
'errmsg' => 'token 无效', //token无效
]);
} catch (JWTException $e) {
return response()->json([
'errcode' => 1001,
'errmsg' => '缺少token' , //token为空
]);
}
}
}
其中JWTAuth::parseToken()->authenticate()用来获取用户信息,传过来的token如果只包含用户id,不可以修改字段名字,不然在用户表里不能查询到相应的用户信息,返回值是完整的用户信息
2、在控制器里获取用户信息(laravel中间件部分知识)
public function userInfo(Request $request){
//只取用户id
$id = $request->get('id');
}
token失效使用JWTAuth::invalidate();
jwt简介与安装上一章