Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending additional parameters to callback uri in socialite package for laravel

Tags:

php

laravel

Im trying to use Socialite package for laravel and I would like to know how to pass additional parameters to callback url. It seems that OAuth allows additional params, but I haven't found any solution for laravel on how to pass them. Currently my methods look like this

public function login($provider)
{
    return Socialite::with($provider)->redirect();
}
    
    
public function callback(SocialAccountService $service, $provider)
{
    $driver = Socialite::driver($provider);
    $user = $service->createOrGetUser($driver, $provider);
    $this->auth()->login($user, true);
    return redirect()->intended('/');
}

Suppose I want to get $user_role variable in my callback method. How do I pass it there?

like image 482
FancyNancy Avatar asked Sep 20 '25 01:09

FancyNancy


2 Answers

You need to use state param if you want to pass some data.

Example for your provider

$provider = 'google';
return Socialite::with(['state' => $provider])->redirect();

Your callback function:

$provider = request()->input('state');
$driver = Socialite::driver($provider)->stateless();

gist example

like image 143
mikicaivosevic Avatar answered Sep 22 '25 14:09

mikicaivosevic


For some reason, Optional Parameters didn't work for me, so i ended up by using session to pass variables from redirect method to the callback method. it's not the best way to do it, but it does the trick.

Simplified example

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\User;
use Socialite;

class FacebookController extends Controller {

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function redirect($my_variable)
    {
        session(['my_variable' => $my_variable]);

        return Socialite::driver('facebook')->redirect();
    }


    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function callback(Request $request)
    {
        try {

            $facebookAccount = Socialite::driver('facebook')->stateless()->user();

            $my_variable = session('my_variable');

            // your logic...

            return redirect()->route('route.name');


        } catch (Exception $e) {


            return redirect()->route('auth.facebook');
        }
    }
}
like image 35
chebaby Avatar answered Sep 22 '25 14:09

chebaby