Laravel 从中间件中获取自定义用户信息
前提:
1.老版本的用户认证在BaseController里面做认证,但是无法适应新的APP用户验证
2.老版本的中间件只是做用户权限验证,不能判断用户是否已失效
要求:
1.做一版本的,能够通过路由中间价进行用户认证(api,app端),以及Controllers 拿到自定义的用户信息
步骤:
1.定义新的中间件
protected $routeMiddleware = [
'refresh' => \App\Http\Middleware\RefreshToken::class,
]
2.新建中间件
<?php
namespace App\Http\Middleware;
class RefreshToken extends BaseMiddleware
{
public function handle($request, Closure $next)
{
// 使用 try 包裹,以捕捉 token 过期所抛出的 TokenExpiredException 异常
try {
// 检查此次请求中是否带有 token,如果没有则抛出异常。
$this->checkForToken($request);
// 检测用户的登录状态,如果正常则通过
if ($this->auth->parseToken()->authenticate() && $this->auth->user()->id) {
$user_id = $this->auth->user()->id;
//两种方式传值至控制器
$request->attributes->add(['user'=>$user]]);
$request->setUserResolver(function () use($user_id,$user){
return $user;
});
}
}catch (JWTException $exception){
return $this->sendError('验证失败!');
}
}
}
3.控制器接受参数 不定义auth_user
public function __get($key)
{
if ($key == 'auth_user') {
return Request::user();
}
}
//如果应用使用了dingo的话,
public function __get($key)
{
$callable = [
'api', 'user', 'auth', 'response',
];
if (in_array($key, $callable) && method_exists($this, $key)) {
return $this->$key();
}
if ($key == 'auth_user') {
//两种方式
return request()->get('user');
return Request::user();
}
throw new .rrorException('Undefined property ' . get_class($this) . '::' . $key);
}
4.使用方式
$this->auth_user
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: