简体   繁体   中英

Laravel login with Socialite (google, facebook, etc) and create an access token of my own app

I am using Laravel Social Authentication with Socialite, I can login successful, but I want to create the access token of my own app, but not the google, twitter and facebook token.

I can create the access token, but it creates everytime when the user login with Socialite. What I want is the token will be created when the user first login with Socialite. Also, the 'user_id' is missing when the token created.

Here's my loginController

   public function handleProviderCallback($provider)
   {
       try {
           $user = Socialite::driver($provider)->stateless()->user();
       } catch (Exception $e) {
           return redirect('/login');
      }
       $authUser = $this->findOrCreateUser($user, $provider);

        Auth::login($authUser,false);

        $user = User::find($authUser['user_id']);

        return $this->getBearerTokenByUser($user, 3, true);
   //    return redirect($this->redirectTo);
      return $user;
  }


   public function findOrCreateUser($providerUser, $provider)
   {
       $account = SocialProvider::whereProviderName($provider)
                  ->whereProviderId($providerUser->getId())
                  ->first();

       if ($account) {
          return $account->user;
       } else {
           $user = User::whereEmail($providerUser->getEmail())->first();

           if (! $user) {
               $user = User::firstOrCreate([
                   'email' => $providerUser->getEmail(),
                   'first_name'  => $providerUser->getName(),

               ]);
           }

           $user->socialProviders()->create([
               'provider_id'   => $providerUser->getId(),
              'provider_name' => $provider,
          ]);
       return $user;
   }

Here is the database data table 'oauth_access_tokens' table 'users_key'

The user_id is missing and the tokens were created twice for the same person (login with google).

The user doesn't have the password because it authentication with Socialite.

you might wanna do some thing like

// Retrieve user by email, or create it with the email and first_name attributes...

User::firstOrCreate(
  ['email' => $providerUser->getEmail()],
  ['first_name'  => $providerUser->getName()]
]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM