0

When issuing access and refresh tokens I send them to the frontend with httpOnly = true. I made a middleware class which checks if the access token has expired and if the refresh token hasn't expired. If both are the case I call the oauth/token route with refresh_token as grant_type.

All of this works, however I'm not sure how to use the authenticated user inside the controllers. Right now I've set the middleware up that when there's a response it sends the new access and refresh token.

class RefreshAccessToken
{
    /* @var AuthController $authController */
    private $authController;

    /**
     * RefreshAccessToken constructor.
     *
     * @param AuthController $authController
     */
    public function __construct(AuthController $authController)
    {
        $this->authController = $authController;
    }

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // User already has an access token
        if ($request->hasCookie('access_token')) {
            return $next($request);
        }

        // User doesn't have an access token and doesn't have a refresh token.
        if (!$request->hasCookie('refresh_token')) {
            return $next($request);
        }

        $response = $next($request);

        $cookies = $this->authController->refreshToken($request);

        return $response
            ->cookie($cookies['access_token'])
            ->cookie($cookies['refresh_token']);
    }
}

Now inside a controller if I want to access the logged in user I always get null as a response:

public function logout()
    {
        dd(auth()->user());
    }
}

Inside the controller's construct method:

$this->middleware('auth:api')->only('logout');

Does anyone know how to handle this use case?

Ezrab_
  • 825
  • 5
  • 19
  • 44
  • @RonvanderHeijden I do use laravel passport to refresh the token, but I want to automaticallyt get a new access token if it has expired via the refresh token. If you'd do this frontend wise (with localStorage) you would check if a request returns 401, and if so you'd know that the access token has expired and then make the refresh token call and try again. When using httpOnly the frontend doesn't need to do any calls for refreshing the access token. – Ezrab_ Jul 02 '20 at 14:44
  • @RonvanderHeijden That seems impossible to me since the expiration time is unknown to the frontend due to the cookie being httpOnly. – Ezrab_ Jul 02 '20 at 15:41
  • @RonvanderHeijden That's definitely not true. – Ezrab_ Jul 02 '20 at 15:50
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/217095/discussion-between-ezrab-and-ron-van-der-heijden). – Ezrab_ Jul 02 '20 at 16:04

0 Answers0