Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

cizario's avatar

How to deal with CORS preflight request (to prefill subscription form using Socialite and jquery Ajax)

hi, i'm building "one single page" app (recently updated to laravel v5.5.32) and i'm combining Socialite with Ajax to retrieve user's data from Linkedin to prefill subscription form and i'm using laravel-cors (v0.11.0) to handle CORS but it seems not working, i tried many ways but still stuck.

i'm showing you my code config/cors.php

    'supportsCredentials' => false,
    'allowedOrigins' => ['http://myapp.local'],
    'allowedOriginsPatterns' => [],
    'allowedHeaders' => ['*'],
    'allowedMethods' => ['*'],
    'exposedHeaders' => [],
    'maxAge' => 0,

kernel.php

protected $routeMiddleware = [
    'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,

    'cors' => \Barryvdh\Cors\HandleCors::class,  // Larvel CORS
];

web.php

Route::group(['middleware' => ['web']], function () {
[...]
    Route::get('/auth/{provider}',             ['as' => 'auth.provider',          'uses' => '\App\Http\Controllers\Front\AuthProviderController@redirectToProvider'])
        ->where(['provider' => 'linkedin|medium'])
        ->middleware('cors')
        ;

    Route::get('/auth/{provider}/callback',    ['as' => 'auth.provider.callback', 'uses' => '\App\Http\Controllers\Front\AuthProviderController@handleProviderCallback'])
        ->where(['provider' => 'linkedin|medium'])
        ->middleware('cors')
        ;
[...]
});

AuthProviderController.php

class AuthProviderController extends Controller 
{
    /**
     * Redirect the user to the GitHub authentication page.
     *
     * @return \Illuminate\Http\Response
     */
    public function redirectToProvider($provider)
    {
        return \Socialite::with($provider)->redirect();
    }

    /**
     * Obtain the user information from GitHub.
     *
     * @return \Illuminate\Http\Response
     */
    public function handleProviderCallback($provider)
    {
        $user = \Socialite::driver($provider)->user();
        // dd($user);
        return response()->json(['user' => $user]);
    }   
}

main.js

$('.auth-provider').click(function(e) {
  e.preventDefault();
  var $provider = $(this);
  $.ajax({
    url: $provider.data('url'),
    type: 'GET',
    headers: {
      'Access-Control-Allow-Origin': 'http://myapp.local'
    },
    contentType: 'application/json',
    dataType: 'json',
    success: function(json) {
        console.log(json);
    },
    error: function(json) {
      console.log(json);
    }
  });
});

i really appreciate any help

0 likes
10 replies
cizario's avatar

@ejdelmonico : i already installed that package but it seems nothing changed and i still keep getting this error in my console :

OPTIONS` https://www.linkedin.com/oauth/v2/authorization?client_id=88xeaq6wh7oz3p&redirect_uri=http%3A%2F%2Fmyapp.local%2Fauth%2Flinkedin%2Fcallback&scope=r_basicprofile+r_emailaddress&response_type=code&state=3MEG7Xefko18u8gsNyQN1Jb1QEIqzh3h3HidlBUn 404 ()

Failed to load https://www.linkedin.com/oauth/v2/authorization?client_id=88xeaq6wh7oz3p&redirect_uri=http%3A%2F%2Fmayapp.local%2Fauth%2Flinkedin%2Fcallback&scope=r_basicprofile+r_emailaddress&response_type=code&state=3MEG7Xefko18u8gsNyQN1Jb1QEIqzh3h3HidlBUn: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://myapp.local' is therefore not allowed access. The response had HTTP status code 404.

if past/go the url i got the linkedin user profile data as expected but it's blocked because of CORS restriction

my ultime concern is how to handle CORS preflight request (OPTIONS method)

i tried before many solutions as per the post of @usamamuneer but ican't figure out way out.

btw, i started from fresh laravel v.5.5.32 installation and Socialite v3.0

cizario's avatar

below is the output of Network tab, hope this can help investigating my problem :

General
Request URL:https://www.linkedin.com/oauth/v2/authorization?client_id=88xeaq6wh7oz3g&redirect_uri=http%3A%2F%2Fmyapp.local%2Fauth%2Flinkedin%2Fcallback&scope=r_basicprofile+r_emailaddress&response_type=code&state=bzlvvhPaCvHzsXsmyf5JBG2btWmuuVGoaipPwqPr
Request Method:OPTIONS
Status Code:404 
Remote Address:@ip:443
Referrer Policy:no-referrer-when-downgrade
Response Headers
cache-control:no-cache, no-store
content-encoding:gzip
content-length:12576
content-security-policy:default-src *; img-src data: blob: *; font-src data: *; style-src 'unsafe-inline' 'self' static-src.linkedin.com *.licdn.com; script-src 'report-sample' 'unsafe-inline' 'unsafe-eval' 'self' platform.linkedin.com spdy.linkedin.com static-src.linkedin.com *.ads.linkedin.com *.licdn.com static.chartbeat.com www.google-analytics.com ssl.google-analytics.com bcvipva02.rightnowtech.com www.bizographics.com sjs.bizographics.com js.bizographics.com d.la4-c1-was.salesforceliveagent.com slideshare.www.linkedin.com; object-src static.licdn.com www.youtube.com; media-src blob: *; child-src blob: lnkd-communities: voyager: *; frame-ancestors 'self'; connect-src * lnkd-communities: voyager:; report-uri https://www.linkedin.com/lite/contentsecurity?f=l
content-type:text/html
date:Sun, 21 Jan 2018 11:30:31 GMT
expires:Thu, 01 Jan 1970 00:00:00 GMT
pragma:no-cache
server:Play
set-cookie:lidc="b=OGST02:g=505:u=1:i=1516534231:t=1516620631:s=BQGqiaqAPFD2R_He_0FHO5MVnatgNJdv"; Expires=Mon, 22 Jan 2018 11:30:31 GMT; domain=.linkedin.com; Path=/
set-cookie:bscookie="v=1&10180121113031ed68e906-2fd6-403a-80d4-014bdcc6bc00AQGr2RfXIPjHufrpn-tHOqtGXsNkx0cw"; domain=.www.linkedin.com; Path=/; Secure; Expires=Tue, 21-Jan-2020 23:08:03 GMT; HttpOnly
set-cookie:bcookie="v=2&1a8a3d4e-2f4c-431d-8a14-71f5865f0c6b"; domain=.linkedin.com; Path=/; Expires=Tue, 21-Jan-2020 23:08:03 GMT
set-cookie:lang=v=2&lang=en-us; Path=/; Domain=linkedin.com
status:404
strict-transport-security:max-age=2592000
vary:Accept-Encoding
x-content-type-options:nosniff
x-frame-options:sameorigin
x-fs-uuid:f2d97321d9cf0b15c00d0858292b0000
x-li-fabric:prod-lor1
x-li-pop:prod-tln1
x-li-proto:http/2
x-li-uuid:8tlzIdnPCxXADQhYKSsAAA==
x-xss-protection:1; mode=block
Request Headers
:authority:www.linkedin.com
:method:OPTIONS
:path:/oauth/v2/authorization?client_id=88xeaq6wh7oz3g&redirect_uri=http%3A%2F%2Fmyapp.local%2Fauth%2Flinkedin%2Fcallback&scope=r_basicprofile+r_emailaddress&response_type=code&state=bzlvvhPaCvHzsXsmyf5JBG2btWmuuVGoaipPwqPr
:scheme:https
accept:*/*
accept-encoding:gzip, deflate, br
accept-language:en-US,en;q=0.9
access-control-request-headers:access-control-allow-origin,content-type,x-requested-with
access-control-request-method:GET
origin:http://myapp.local
user-agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36
Query String Parameters
client_id:88xeaq6wh7oz3g
redirect_uri:http://myapp.local/auth/linkedin/callback
scope:r_basicprofile r_emailaddress
response_type:code
state:bzlvvhPaCvHzsXsmyf5JBG2btWmuuVGoaipPwqPr
cizario's avatar

handling CORS preflight options request is very annoying and tricky. i tried many solutions with no luck.

does Linkedin API support CORS preflight options request ?

anybody could help me out ?

ravipula's avatar

@cizario , Were you able solve this issue. If you did can you please put in how you did. I am experiencing the same issue. I am trying to implement login with google, when socialite redirect function is executed it is throwing up the "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin URL is therefore not allowed access. The response had HTTP status code 405." Thanks in Advance.

artcore's avatar

Did you create an 'options' route? $router->options('same endpoint as your get/post request','Controller@optionsResponse'); You can just return an empty string, 200 response code.

That did it for me. (I'm not using a closure to keep route caching)

ravipula's avatar

@artcore I do have the options route but no change. To explain my scenario, I have a login with google button(ReactJS) which does axios.get request through api route in api.php which goes to the Socialite redirect function. This produces the targetUrl with the client credentials but this url thrown error in the console saying the CORS issue " No 'Access-Control-Allow-Origin' header is present on the requested resource." I'm not sure what's going wrong here as i even have the barryvdh/laravel-cors package to handle these. I have the callback route in the web.php file. i'm stuck at this point. Thank you guys appreciate your help @cizario @artcore

artcore's avatar

Here's my middleware


namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Response;

class Cors
{
  /**
   * Handle an incoming request.
   *
   * @param  \Illuminate\Http\Request $request
   * @param  \Closure $next
   * @return mixed
   */
  public function handle($request, Closure $next)
  {
    /* @var $response Response */
    $response = $next($request);

    $headers = [
      'Access-Control-Allow-Origin'   => '*',
      'Access-Control-Allow-Methods' => 'POST,OPTIONS',
//      'Access-Control-Max-Age'       => 604800,
      'Access-Control-Allow-Headers' => 'X-Requested-With, Origin, X-Csrftoken, Accept',
    ];
    return $response->withHeaders($headers);
  }
}```


In the Http\Kernel
No throttling or bindings middleware in this case

Middleware groups
```'api' => [
      'cors'
    ],

protected $routeMiddleware = [
    'auth'       => \Illuminate\Auth\Middleware\Authenticate::class,
    'cors'       => \App\Http\Middleware\Cors::class,
    'restricted' => \App\Http\Middleware\RestrictedAccess::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings'   => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'can'        => \Illuminate\Auth\Middleware\Authorize::class,
    'guest'      => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle'   => \Illuminate\Routing\Middleware\ThrottleRequests::class,
  ];


Perhaps it is of help. My case is a bit different - a custom analytics collector - and I don't use axios. If you have Content-Type json/application the options will always be sent before the actual request data. Since I needed optimum performance I chose to use text/html content type (multi-part/form-data sends a bad object in Chrome sometimes) and json_decode it myself

Please or to participate in this conversation.