Cross-Origin API calls with Laravel middleware

29 Views Asked by At

In Laravel 5.7, I am attempting to expose a route in the API that uses the built-in session and authentication features of my Laravel app to guard against people using it who do not have a current session in the web app. A separate application on a different domain is to call this route via a fetch request. If it comes from a browser with a current session in the laravel app, it should pass; otherwise, it should 401.

Here is some relevant code that I am trying:

The routes:

Route::post('/v2/instances/{name}', 'API\v2\InstanceController@insert')->middleware([\Illuminate\Session\Middleware\StartSession::class, 'special_cors', 'cookie_token']);

Route::options('/v2/instances/{name}', 
    function () {  
        return response()->json([''], 204);
    }
)->middleware(['special_cors']);

Special Cors middleware to allow the cross-origin fetch request to pass all cookies:

namespace App\Http\Middleware;

use Closure;
 
class SpecialCors
{
    public function handle($request, Closure $next)  
    {  
        $response = $next($request);    
        $response->header('Access-Control-Allow-Origin', 'http://localhost'); 
        $response->header('Access-Control-Allow-Credentials', 'true');  
        $response->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');  
        $response->header('Access-Control-Allow-Headers', 'Content-Type, Authorization, x-csrf-token');  
        return $response;  
    }  
}

Validate cookie token middleware, attempting to assess if a user is authenticated:

  namespace App\Http\Middleware;  
  
  use Closure;  
  use Illuminate\Http\Request;  
  use Illuminate\Support\Facades\Auth;  
    
  class ValidateCookieToken  
  {  
      public function handle(Request $request, Closure $next)  
      {  
          if (Auth::check()) {  
              // The user is logged in  
              return $next($request);  
          } else {  
              // The user is not logged in  
              return response('Unauthorized', 401);  
          }  
      }  
    }

When I hit this route with my fetch request from localhost, I set credentials: include and can confirm that the session cookie and the XSRF-TOKEN are successfully attached as part of the cookie header. My Cors middleware is working well. It fires the callback and does not return the Cors error in the browser. However, it always Auth::check() fails, and it returns unauthorized even though in the same browser, I have no problem navigating the routes of the web app. Why do my cross-origin fetch requests to API fail when I have an otherwise valid session? What am I missing?

0

There are 0 best solutions below