spatie / laravel-cors

Send CORS headers in a Laravel application
https://spatie.be/en/opensource/laravel
MIT License
603 stars 59 forks source link

Socialite, Ajax and CORS issue #9

Closed cizario closed 6 years ago

cizario commented 6 years ago

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

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

return [
    'cors_profile' => Spatie\Cors\CorsProfile\DefaultProfile::class,
    'default_profile' => [
        'allow_origins' => [
            'http://myapp.local',
        ],
        'allow_methods' => [
            // 'POST',
            'GET',
            'OPTIONS',
            // 'PUT',
            // 'PATCH',
            // 'DELETE',
        ],

        'allow_headers' => [
            'Content-Type',
            'X-Auth-Token',
            'Origin',
            'Authorization',
        ],
        'max_age' => 60 * 60 * 24,
    ],
];

kernel.php

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    \App\Http\Middleware\TrustProxies::class,
    \Spatie\Cors\Cors::class, 
];

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']) ;

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

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',
    contentType: 'application/json',
    dataType: 'json',
    success: function(json) {
      console.log(json);
    },
    error: function(json) {
      console.log(json);
    }
  });
});

i really appreciate any help.

cizario commented 6 years ago

i 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.
cizario commented 6 years ago

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
freekmurze commented 6 years ago

This package sends cors headers to requests towards your application. Seems like the failing requests are requests to LinkedIn. This package can't help you with those.