Switch to the Spatie CORS package as it is better written and handles preflight very well.
Jan 21, 2018
10
Level 1
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
Please or to participate in this conversation.