Laravel JWT auth和refresh整合

Laravel JWT 擴展的討論沒有結論:php

https://github.com/tymondesigns/jwt-auth/issues/186git

本身整的,整合jwt.auth和jwt.refresh的代碼,作出了一個新的middlewaregithub

<?php

/*
 * This file is part of jwt-auth.
 *
 * (c) Sean Tymon <tymon148@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace App\Http\Middleware;

use Tymon\JWTAuth\Middleware\BaseMiddleware;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;

class APIAuthenticate extends BaseMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, \Closure $next)
    {
        $jwtAuth = $this->auth->setRequest($request);
        if (! $token = $jwtAuth->getToken()) {
            return $this->respond('tymon.jwt.absent', 'token_not_provided', 400);
        }

        try {
            $user = $this->auth->authenticate($token);
        } catch (TokenExpiredException $e) {
            try {
                $newToken = $jwtAuth->parseToken()->refresh();
                $user = $this->auth->authenticate($newToken);
                if (! $user) {
                    return $this->respond('tymon.jwt.user_not_found', 'user_not_found', 404);
                }

                $this->events->fire('tymon.jwt.valid', $user);

                $response = $next($request);
                $response->headers->set('Authorization', 'Bearer '.$newToken);
                
                return $response;
            } catch (TokenExpiredException $e) {
                return $this->respond('tymon.jwt.expired', 'token_expired', $e->getStatusCode(), [$e]);
            } catch (JWTException $e) {
                return $this->respond('tymon.jwt.invalid', 'token_invalid', $e->getStatusCode(), [$e]);
            }
        } catch (JWTException $e) {
            return $this->respond('tymon.jwt.invalid', 'token_invalid', $e->getStatusCode(), [$e]);
        }

        if (! $user) {
            return $this->respond('tymon.jwt.user_not_found', 'user_not_found', 404);
        }

        $this->events->fire('tymon.jwt.valid', $user);

        return $next($request);
    }
}

其實就是將jwt.auth和jwt.refresh的代碼進行整合,將該middleware做爲api接口的認證中間件就能夠了。api

可是有一個要注意的ide

之後獲取當前用戶的方法須要糾正一下:this

// 文檔裏的方式
$user = JWTAuth::parseToken()->authenticate();

// 新的方式spa

$user = JWTAuth::authenticate(JWTAuth::getToken());code

即只能獲取JWTAuth當前的token(可能已經被更新過的),不能再從request裏解析token(parseToken 請求帶過來的,可能被更新了)orm

新的方式可能從語義上不太直觀,能夠考慮再封裝一下,自由發揮。。。jwt

==========================================================

必須記得,請求放回的結果裏須要檢查 Header是否有 Authorization 字段,有的話必須更新本地的token

相關文章
相關標籤/搜索