Search code examples
laravelcorslaravel-passport

How to add CORS middleware with auth:api passport middleware in Laravel?


I have used Laravel Passport for authenticated endpoints. I am facing CORS issue for those APIs.

In app/Http/Middleware/Cors.php

<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', "*")
                ->header('Access-Control-Allow-Methods', "PUT,POST,DELETE,GET,OPTIONS")
                ->header('Access-Control-Allow-Headers', "Accept,Authorization,Content-Type");
    }
}

In app/Http/Kernel.php, added in the middleware array

\App\Http\Middleware\Cors::class,

In the routes/api.php,

Route::post('auth/login', 'PassportController@login'); //working 
Route::middleware('auth:api')->group(function () {
Route::get('vehicle/all', 'VehicleController@getVehicles'); //not working: facing CORS error
});

I have used the auth:api (Laravel passport) for authorization. I am facing CORS error for the endpoints in the auth:api group. Endpoints which are outside the group like 'auth/login' are working fine. How to handle cors error inside Route::middleware('auth:api') group?


Solution

  • You need to specify the domain allowed, the wildcard '*' is not accepted by browsers anymore.

    If you have multiple domains calling your api, you can make it dynamic with $_SERVER['HTTP_HOST']

    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    
    class Cors
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            $domain = $request->getHost();
            // or $domain =  $_SERVER['HTTP_HOST'];
            return $next($request)
                ->header('Access-Control-Allow-Origin', $domain)
                    ->header('Access-Control-Allow-Methods', "PUT,POST,DELETE,GET,OPTIONS")
                    ->header('Access-Control-Allow-Headers', "Accept,Authorization,Content-Type");
        }
    }