jwt的安装
composer require tymon/jwt-auth
config.php中添加服务提供程序
'providers' => [
...
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
]
发布配置文件
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider
生成密钥
php artisan jwt:secret
更改用户模型
//倘若不想使用默认的User.php auth模型的话,自己手动新建一个模型,并在auth.php中配置
namespace App\DB;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Tymon\JWTAuth\Contracts\JWTSubject;
class Staff extends Authenticatable implements JWTSubject
{
protected $table = 'staff';
protected $primaryKey = 'id';
use Notifiable;
public function getJWTIdentifier()
{
return $this->getKey();
// TODO: Implement getJWTIdentifier() method.
}
public function getJWTCustomClaims()
{
return [];
// TODO: Implement getJWTCustomClaims() method.
}
}
配置auth guard
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
...
'guards' => [
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
···
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\DB\Staff::class,
'table' =>'user_basic'
],
],
添加路由api.php
创建控制器
php artisan make:controller AuthController
namespace App\Http\Controllers;
use App\DB\Staff;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Response;
use Tymon\JWTAuth\Facades\JWTAuth;
class AuthController extends Controller
{
public function __construct()
{
$this->middleware('RefreshToken', ['except' => 'login']);
}
public function login(Request $request)
{
if(\auth()->check()){
//如果有有效token,则先手动失效
\auth()->invalidate();
}
$input = request(['work_num', 'password']);
// 验证规则,由于业务需求,这里我更改了一下登录的用户名,使用手机号码登录
$rules = [
'work_num' => [
'required',
],
'password' => 'required|numeric',
];
$messages = [
'required'=>":attribute不能为空",
'numeric'=>":attribute必须为数字",
];
$attributes = [
'work_num'=>"工号",
'password'=>"密码"
];
$validator = \Validator::make($input,$rules,$messages,$attributes);
if($validator->fails()){
$error = $validator->errors()->first();
return response()->json([
'code'=>"201",
'error'=>$error
]);
}
// 验证参数,如果验证失败,则会抛出 ValidationException 的异常
$params = $this->validate($request, $rules);
if ($user = Staff::where(['work_num' => $input['work_num'], 'password' => md5(md5($input['password']))])->first()) {
// $token = JWTAuth::fromUser($user);
$token = auth('api')->login($user);
} else {
return response()->json(['result' => '账号或密码错误.']);
}
return response()->json(
[
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60
]
);
}
public function me(){
$user = \auth('api')->user();
return response()->json(compact('user'));
}
public function logout()
{
\auth()->logout();
return response(['message' => '退出成功']);
}
中间件
php artisan make:middleware RefreshToken
kernel.php
protected $routeMiddleware=[
···
'RefreshToken'=>\App\Http\Middleware\RefreshToken::class
···
]
中间件内容
public function handle($request, Closure $next)
{
$this->checkForToken($request);
try{
if($this->auth->parseToken()->authenticate()){
return $next($request);
}
throw new UnauthorizedHttpException('jwt',"未登陆");
}catch (TokenExpiredException $exception){
try{
$token = $this->auth->refresh();
Auth::guard('api')->onceUsingId($this->auth->manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray()['sub']);
}catch (JWTException $exception){
//刷新过期
throw new UnauthorizedHttpException('jwt',"登录失效,请重新登录");
}
return $this->setAuthenticationHeader($next($request),$token);
}catch (TokenBlacklistedException $exception){
throw new UnauthorizedHttpException('jwt',"登录失效,请重新登录");
}
}