RainDeer
3 months ago

Not able to get Socialite user

Posted 3 months ago by RainDeer

I have created a socialite registration process using the spotify provider. The authentication works fine, the user is created and logged in. But after registration I want to fetch the users Spotify auth token using: Socialite::driver('spotify')->stateless()->user() or Socialite::driver('spotify')->user().

The response I get is 400 Bad Request` response: {"error":"invalid_request","error_description":"code must be supplied"}

Here is my callback function

public function handleProviderCallback(\App\SocialAccountService $accountService, $provider)
    {

        try {
            $user = Socialite::with($provider)->user();
        } catch (\Exception $e) {
            return redirect('/login');
        }

        $authUser = $accountService->findOrCreate(
            $user,
            $provider
        );
        auth()->login($authUser);

        return redirect()->to('/home');
    }

SocialAccountService class

<?php

namespace App;

use Laravel\Socialite\Contracts\User as ProviderUser;

class SocialAccountService
{
    public function findOrCreate(ProviderUser $providerUser, $provider)
    {
        $account = LinkedSocialAccount::where('provider_name', $provider)
                   ->where('provider_id', $providerUser->getId())
                   ->first();

        if ($account) {
            return $account->user;
        } else {

            $account = new LinkedSocialAccount([
                'provider_id'   => $providerUser->getId(),
                'provider_name' => $provider
            ]);

            $user = User::where('email', $providerUser->getEmail())->first();

            if (! $user) {
                $user = User::create([  
                    'email' => $providerUser->getEmail(),
                    'name'  => $providerUser->getName(),
                ]);
            }

            $account->user()->associate($user);
            $account->save();

        return $user;

        }
    }
}

And HomeController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Socialite;
use Auth;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        //$user = Socialite::driver('spotify')->user();
        $user = Socialite::driver('spotify')->stateless()->user();
        var_dump($user);
        return view('home');
    }
}

What am I doing wrong?

Please sign in or create an account to participate in this conversation.