Search code examples
laravelapilaravel-passport

Getting error: "Unauthenticated" with Laravel Passport


I'm trying to create a single page app with Laravel/Passport as the API backend. To sign up, I create my user as usual, then use Passport's ApiTokenCookieFactory to generate my JWT cookie like so:

// api_success is a response macro
    return $this->response->api_success('User successfully created')
       ->withCookie($this->cookie->make($newUser->getModel()->getKey(), $request->header('X-CSRF-TOKEN')));

You can assume that $this->cookie is the container's resolved cookie factory. This all works fine and I get a laravel_token cookie with the JWT.

When I go to make a request though, for example to api/users/me, I get this response:

{
    "error": "Unauthenticated."
}

I'm sending the CSRF token, I'm setting X-Requested-With to XMLHttpRequest, and the cookie is being sent along with the request.

The /api/users/me route has the api:auth middleware, so I'm at a loss as to what I'm doing wrong. If anyone has any suggestions they'd be greatly appreciated <3


Solution

  • I've solved the issue I was having, if anyone gets here in the future, note that cookies are not encrypted by default!! Make sure to either add the encrypt cookies middleware to your route, or encrypt cookies manually. My god I was so happy when I figured this out. It turns out that the passport guard was trying to decrypt my unencrypted cookie and silently (!!) failing.