Search code examples
corsaxioslaravel-passportlaravel-7

Laravel 7 Passport : blocked by CORS policy


When I make the following axios request to my Laravel 7.3 Passport API:

let url = 'http://laravel.test/oauth/token'

let params = {
  client_id:  4,
  client_secret: 'FBkMiLI8ecdb4A8OhLRDGS1SasZP5NT7i9Qpp7bP',
  grant_type: 'password',
  username: 'me@home.com',
  password: '1qaz@WSX',
  scope: '*'
}

let headers = {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS',
    'Access-Control-Allow-Headers': 'Content-Type'
  }

axios.post(url, params, headers)
.then(response => {
      this.access_token = response['data']['access_token'];
      this.get_users_data()
  })
.catch(response => {
// eslint-disable-next-line
    console.log(response)
});

I get this error in my javascript console:

Access to XMLHttpRequest at 'http://laravel.test/oauth/token' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Also, config/cors.php in Laravel 7.3 is configured to allow anything (by default):

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Cross-Origin Resource Sharing (CORS) Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure your settings for cross-origin resource sharing
    | or "CORS". This determines what cross-origin operations may execute
    | in web browsers. You are free to adjust these settings as needed.
    |
    | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
    |
    */

    'paths' => ['api/*'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => false,

];

What's wrong in my request ?


Solution

  • Nothing's wrong with your request. Your API resource has a CORS policy which restricts what domains may access the resource. The error you're getting is telling you that the resource does not have a CORS header allowing access from the calling domain.

    You need to set the CORS policy to whitelist your domain: http://localhost:3000. You may find this article, Handling CORS in a Laravel Application, helpful:

    Recently we released laravel-cors. This package can add the necessary CORS headers of your Laravel app.