lundi 30 octobre 2017

Laravel/Vue - refreshing JWT token

I am using tymon jwt auth package in laravel for token authentication and I am trying to refresh a JWT token if it is expired, I have set up a middleware AuthenticateToken, that looks like this:

class AuthenticateToken
{
    public function handle($request, Closure $next)
    {
        try
        {
            if (! $user = JWTAuth::parseToken()->authenticate() )
            {
                return response()->json([
                    'code'   => 401,
                    'response' => null
                ]);
            }
        }
        catch (TokenExpiredException $e)
        {
            // If the token is expired, then it will be refreshed and added to the headers
            try
            {
                $refreshed = JWTAuth::refresh(JWTAuth::getToken());
                $user = JWTAuth::setToken($refreshed)->toUser();
                header('Authorization: Bearer ' . $refreshed);
            }
            catch (JWTException $e)
            {
                return response()->json([
                    'code'   => 403,
                    'response' => null
                ]);
            }
        }
        catch (JWTException $e)
        {
            return response()->json([
                'code'   => 401,
                'response' => null
            ]);
        }

        // Login the user instance for global usage
        Auth::login($user, false);

        return  $next($request);
    }
}

And I am using that middleware on my routes:

    Route::group(['prefix' => 'intranet', 'middleware' => ['token']], function () {
        Route::get('intranet-post', 'Api\IntranetController@index');
    });

And in Vue I have set up the axios and refreshing of the token like this:

// Apply refresh(ing) token
BACKEND.defaults.transformResponse.push((data, headers) => {
  if (headers.authorization && store('token', headers.authorization)) {
    BACKEND.defaults.headers.common.authorization = headers.authorization;
  }
  return data;
});

BACKEND.defaults.transformRequest.push((data, headers) => {
  headers.authorization = `Bearer ${load('token')}`;
});

Vue.prototype.$http = axios;
Vue.prototype.$backend = BACKEND;

function store(key, value) {
  try {
    let oldLength = localStorage.length;
    localStorage.setItem(key, value);
    return !(localStorage.length > oldLength); // Returns true on write error
  }
  catch (err) {
    return true;
  }
}

function load(key) {
  try {
    return localStorage.getItem(key);
  }
  catch (err) {
    return null;
  }
}

But, on expiration of the token I still get 403 response. How can I fix this?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2yXPTpb
via IFTTT

Aucun commentaire:

Enregistrer un commentaire