简体   繁体   English

Laravel使用Socialite(Google,Facebook等)登录并创建我自己的应用程序的访问令牌

[英]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. 我正在将Laravel Social Authentication与Socialite一起使用,我可以成功登录,但是我想创建自己的应用程序的访问令牌,但不能创建google,twitter和facebook令牌。

I can create the access token, but it creates everytime when the user login with Socialite. 我可以创建访问令牌,但是每次用户使用Socialite登录时都会创建访问令牌。 What I want is the token will be created when the user first login with Socialite. 我要的是在用户首次使用Socialite登录时将创建令牌。 Also, the 'user_id' is missing when the token created. 此外,创建令牌时会丢失“ user_id”。

Here's my loginController 这是我的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' 这是数据库数据表“ oauth_access_tokens” 表“ users_key”

The user_id is missing and the tokens were created twice for the same person (login with google). 缺少user_id,并且为同一个人创建了两次令牌(使用google登录)。

The user doesn't have the password because it authentication with Socialite. 用户没有密码,因为它已通过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()]
]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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