JWT判断用户是否登录
1.自定义一个auth的guard,并且继承与JWTGuard
<?php
/**
* Created by PhpStorm.
* User: Winner
* Date: 2019/1/18
* Time: 21:20
*/
namespace App\Auth;
use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Http\Request;
use Illuminate\Contracts\Session\Session;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Tymon\JWTAuth\JWT;
use Tymon\JWTAuth\JWTGuard;
class JWTSessionGuard extends JWTGuard
{
protected $session;
public function __construct(JWT $jwt, UserProvider $provider, Request $request, Session $session)
{
$this->session = $session;
parent::__construct($jwt, $provider, $request);
}
public function login(JWTSubject $user)
{
$token = $this->jwt->fromUser($user);
$this->setToken($token)->setUser($user);
$this->updateSession($user->id);
return $token;
}
//设置session的判断字段
protected function updateSession($id)
{
$this->session->put($this->getName(), $id);
$this->session->migrate(true);
}
public function getName()
{
return 'login_jwt_'.sha1(static::class);
}
public function webCheck() {
$id = $this->session->get($this->getName());
return !is_null($this->provider->retrieveById($id));
}
}
2.更改 app/Providers/AuthServiceProvider.php 文件
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use App\Auth\JWTSessionGuard;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
$this->extendAuthGuard();
//
}
public function extendAuthGuard()
{
$this->app['auth']->extend('jwt_session', function ($app, $name, array $config) {
$guard = new JWTSessionGuard(
$app['tymon.jwt'],
$app['auth']->createUserProvider($config['provider']),
$app['request'],
$app['session.store']
);
$app->refresh('request', $guard, 'setRequest');
return $guard;
});
}
}
3.修改 config/auth.php
'api' => [
'driver' => 'jwt_session',
'provider' => 'users',
],
4.添加中间件
<?php
namespace App\Http\Middleware;
use Closure;
class CheckWebAuth
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
//webCheck 自定义 查看文档
if (auth('api')->webCheck()) {
return $next($request);
}
return redirect()->route('auth.login.create');
}
}
//在 kernel.php 下 $routeMiddleware 中注册中间件
'check.webauth' => \App\Http\Middleware\CheckWebAuth::class,
使用中间件