API route (/api) authentication not working in laravel

Thanks again for your patience here.

I consulted with a few folks internally and wanted to revisit something I mentioned earlier about cookies. What we’re exploring with the API token is best used in the case where you have an API that’s accessed by something that requires tokens (like a native app or another machine) as well. If you’re just getting data to, say, asynchronously load a profile or content based on preferences, you can probably get away with the cookie-based auth for those endpoints (covered in links above). You’ll need to make sure CORS is not active for your server (so other domains cannot use these cookies to get the same data) and use CSRF tokens if you ever start to accept POST requests.

With that said, I’ll pick up from where the previous steps above left off:

  1. Create a custom middleware to look for an access token (Gist) and save it to a cookie if there is one.

  2. Register this middleware in your HTTP Kernel:

// app/Http/Kernel.php
class Kernel extends HttpKernel {
    // ...
    protected $routeMiddleware = [
        // ...
        'setToken' =>  \App\Http\Middleware\SetAccessTokenCookie::class,
    ];
    // ...
}
  1. Now, we need to attach the setToken middleware to your callback route. This will run the code exchange early and set the user, which will be picked up by the controller. The final route should look like this:
Route::get( '/auth0/callback', '\Auth0\Login\Auth0Controller@callback' )
    ->name( 'auth0-callback' )
    ->middleware('setToken');
  1. Finally, we’ll exclude this cookie from encryption because it does not contain any sensitive information. In app/Http/Middleware/EncryptCookies.php, add the constant use for the cookie name:
protected $except = [
    \App\Http\Middleware\SetAccessTokenCookie::COOKIE_NAME
];

Now, when you login, you should have an access_token cookie accessible by JS with the token from Auth0. If you test that against the API built with the previous steps you should be able to access the endpoints there.

Hopefully this helps out with authentication for anything else that might be consuming this API.

1 Like