Kos-Mos
Kos-Mos

Reputation: 707

Laravel Socialite works in Postman but not in SPA

I am in a weird situation where when i test the request to /auth/social/facebook in postman i am successfully redirected to the facebook page, but when making a request to the same route from my spa i get CORS related errors:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.facebook.com/v3.3/dialog/oauth?client_id=240805606930310&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fapi%2Fauth%2Fsocial%2Ffacebook%2Fcallback&scope=email&response_type=code. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 400.

In my code i have:

Route:

Route::get('/auth/social/{provider}', [AuthController::class, 'socialRedirect']);

Controller:

public function socialRedirect($provider){
        return Socialite::driver($provider)->stateless()->redirect();
    }

and in CORS config:

<?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/*', 'sanctum/csrf-cookie'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => false,

];

Upvotes: 0

Views: 1463

Answers (2)

jmberon
jmberon

Reputation: 195

This worked for me:

Route::get('/auth/login', function () {
    return Inertia::location(Socialite::driver('auth0')->redirect());    
})

Check info on external redirects here: https://inertiajs.com/redirects

Upvotes: 4

Hari Upreti
Hari Upreti

Reputation: 101

I am not sure if you are using InertiaJS or not, but if you are using it for the SPA connector on laravel app, and performing modification on header information for allowing the origin or doing the redirect which may not work, because the request is made up on your inertia request. Instead you can return a Inertia response through which Inertia will able to redirect the request on your desired location.

    $redirectUrl = Socialite::driver('driverProvider')->redirect()->getTargetUrl();
    return response('', 409)->header('X-Inertia-Location', $redirectUrl);

There is some helpful information on this. https://inertiajs.com/redirects#external-redirects

Upvotes: 6

Related Questions