Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Access-Control-Allow-Origin header response in Laravel 5.3 Passport

I'm new to Laravel and am doing some Laravel 5.3 Passport project with OAuth2.0 password grant. When I curl the API with the params it responds with token. However, in browser it needs an additional security that the endpoint should add because my request is coming from localhost while the API is located in my VM. Here's the error:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 400. 

I know what the issue is but I don't know where to put to include that header since this is a third party app.

Thank you in advance experts. Please help.

like image 584
user3856437 Avatar asked Sep 10 '16 18:09

user3856437


People also ask

How do I enable CORS policy in laravel?

The simplest method to enable CORS is to add Access-Control-Allow-Origin:* to the response header from WEB servers, which allows CORS from any source. If you want to limit the source, you should specify the domain in the configuration such as Access-Control-Allow-Origin:https://hogehoge.com .

How do I fix CORS header Access-Control allow Origin missing?

If the server is under your control, add the origin of the requesting site to the set of domains permitted access by adding it to the Access-Control-Allow-Origin header's value. You can also configure a site to allow any site to access it by using the * wildcard. You should only use this for public APIs.


1 Answers

The simple answer is to set the Access-Control-Allow-Origin header to localhost or *. Here's how I usually do it:

Create a simple middleware called Cors:

php artisan make:middleware Cors 

Add the following code to app/Http/Middleware/Cors.php:

public function handle($request, Closure $next) {     return $next($request)         ->header('Access-Control-Allow-Origin', '*')         ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); } 

You can replace the * with localhost or keep it as it is.

Next step is to load the middleware. Add the following line to the $routeMiddleware array in app/Http/Kernel.php.

'cors' => \App\Http\Middleware\Cors::class,  

And the final step is to use the middleware on the routes to which you want to set the access origin headers. Assuming you are talking about the new api routes in laravel 5.3, the place to do it is app/Providers/RouteServiceProvider.php, inside the mapApiRoutes() function (you can remove or comment the previous code of the function):

    Route::group([         'middleware' => ['api', 'cors'],         'namespace' => $this->namespace,         'prefix' => 'api',     ], function ($router) {          //Add you routes here, for example:          Route::apiResource('/posts','PostController');     }); 
like image 113
haris Avatar answered Sep 17 '22 15:09

haris