Last active
June 4, 2020 03:36
-
-
Save ArnoldLC/c499cbc86ab0078b9d332651d9420321 to your computer and use it in GitHub Desktop.
Actualización de jwt token en LUMEN usando tymon/jwt-auth. Reference: https://github.com/tymondesigns/jwt-auth/issues/1355
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Archivo de configuración para hacer las peticiones usando 'axios' | |
*/ | |
import axios from "axios"; | |
import store from "@/store/index" | |
import router from "@/router/index" | |
const baseApiAddress = `${process.env.VUE_APP_API_URL}:${process.env.VUE_APP_API_PORT}/api` | |
const api = axios.create({ | |
baseURL: `${process.env.VUE_APP_API_URL}:${process.env.VUE_APP_API_PORT}/api`, | |
}); | |
api.interceptors.request.use(config => { | |
if (config.baseURL === baseApiAddress) { | |
const token = JSON.parse(localStorage.getItem("vuex")) | |
console.log(token) | |
if (token.auth.token) { | |
config.headers.Authorization = token.auth.token | |
} | |
} | |
// console.log(config) | |
return config; | |
}, error => { | |
return Promise.reject(error) | |
}) | |
api.interceptors.response.use( | |
(response) => { | |
//console.log(response) | |
const newToken = response.headers.authorization; | |
//console.log(newToken) | |
if (newToken) store.commit('updateToken', newToken) | |
//console.log(response.data) | |
return response; | |
}, | |
(error) => { | |
console.log("Error de petición anterior") | |
if (error.response.status === 401) { | |
store.commit("deleteToken"); | |
router.push("/login"); | |
} | |
return Promise.reject(error); | |
} | |
); | |
export default api; | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Registrar el middleware creado bajo el nombre 'jwt' | |
*/ | |
<?php | |
... | |
$app->routeMiddleware([ | |
'auth' => App\Http\Middleware\Authenticate::class, | |
'jwt' => App\Http\Middleware\RefreshToken::class, // Middleware a registrar | |
]); | |
... |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Modificar middleware para que el archivo JS del front pueda leer el header y actualizar el token para | |
las siguientes peticiones. | |
*/ | |
<?php | |
/** | |
* Location: /app/Http/Middleware | |
*/ | |
namespace App\Http\Middleware; | |
use Closure; | |
class CorsMiddleware | |
{ | |
/** | |
* Handle an incoming request. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param \Closure $next | |
* @return mixed | |
*/ | |
public function handle($request, Closure $next) | |
{ | |
$headers = [ | |
'Access-Control-Expose-Headers' => ['authorization'], | |
'Access-Control-Allow-Origin' => '*', | |
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE', | |
'Access-Control-Allow-Credentials' => 'true', | |
'Access-Control-Max-Age' => '86400', | |
'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With' | |
]; | |
if ($request->isMethod('OPTIONS')) { | |
return response()->json('{"method":"OPTIONS"}', 200, $headers); | |
} | |
$response = $next($request); | |
foreach ($headers as $key => $value) { | |
$response->header($key, $value); | |
} | |
return $response; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Middleware que hará el trabajo de actualizar el token las veces que sea necesario. | |
*/ | |
<?php | |
namespace App\Http\Middleware; | |
use Carbon\Carbon; | |
use Illuminate\Support\Facades\Cache; | |
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; | |
use Tymon\JWTAuth\Exceptions\JWTException; | |
use Tymon\JWTAuth\Exceptions\TokenExpiredException; | |
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware; | |
class RefreshToken extends BaseMiddleware | |
{ | |
public function handle($request, \Closure $next) | |
{ | |
$this->checkForToken($request); | |
try { | |
if (!$this->auth->parseToken()->authenticate()) { | |
throw new UnauthorizedHttpException('jwt-auth', 'User not found'); | |
} | |
$payload = $this->auth->manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray(); | |
return $next($request); | |
} catch (TokenExpiredException $t) { | |
$payload = $this->auth->manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray(); | |
$key = 'block_refresh_token_for_user_' . $payload['sub']; | |
$cachedBefore = (int) Cache::has($key); | |
if ($cachedBefore) { | |
\Auth::onceUsingId($payload['sub']); | |
return $next($request); | |
} | |
try { | |
$newToken = $this->auth->refresh(); | |
$gracePeriod = $this->auth->manager()->getBlacklist()->getGracePeriod(); | |
$expiresAt = Carbon::now()->addSeconds($gracePeriod); | |
Cache::put($key, $newToken, $expiresAt); | |
} catch (JWTException $e) { | |
throw new UnauthorizedHttpException('jwt-auth', $e->getMessage(), $e, $e->getCode()); | |
} | |
} | |
$response = $next($request); | |
return $this->setAuthenticationHeader($response, $newToken); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Modificar tu archivo de rutas de tal manera que las rutas que necesitan ser autenticadas pasen por el middleware | |
*/ | |
<?php | |
... | |
$router->group(['middleware' => 'jwt'], function () use ($router) { | |
$router->group(['prefix' => 'users'], function () use ($router) { | |
$router->get('/getWithFarmacia', 'UserController@getAllUsersWithPharmacies'); | |
}); | |
... | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment