【问题标题】:Vue SPA and Laravel SocialiteVue SPA 和 Laravel 社交名流
【发布时间】:2019-05-16 23:42:05
【问题描述】:

我正在尝试使用 laravel socialite 无状态选项通过 laravel api 后端集成社交登录,因为我正在使用 vuejs 构建单页应用程序,并且一切都通过 http api 调用完成。

但是我遇到了社交回调的问题,当前的回调正在发送到 laravel 后端并且它可以工作,但是现在我想在开始身份验证之前将用户返回到同一页面,关于如何解决的任何想法这 ?

public function handleProviderCallback($provider)
{
    $user = Socialite::driver($provider)->stateless()->user();

    // dont know how to return the user to the last page on vue
} 

【问题讨论】:

    标签: laravel vue.js laravel-socialite


    【解决方案1】:

    我正在研究类似的东西,我找到了解决方案。代码基于这个伟大的入门主题:https://github.com/cretueusebiu/laravel-vue-spa

    --

    在handleProviderCallback()中,假设你使用的是Passport API Authentication,你可以试试这个Controller:

    public function handleProviderCallback($provider)
        {
            $user = Socialite::driver($provider)->stateless()->user();
    
            /* HERE CREATE USER WITH YOUR APP LOGIC. If email is unique... */
    
            // Login the created user
            Auth::login($user, true);
    
            // Get the username (or wathever you want to return in the JWT).
            $success['name'] = Auth::user()->name;
            // Create a new access_token for the session (Passport)
            $success['token'] = Auth::user()->createToken('MyApp')->accessToken;
    
            // Create new view (I use callback.blade.php), and send the token and the name.
            return view('callback', [
                'name' => $success['name'],
                'token' => $success['token'],
            ]);
        }
    

    对于 callback.blade.php 视图,您唯一需要做的就是将请求的令牌和用户名发送到 Vue 应用程序。为此,您可以使用 window.postMessage() 方法,该方法允许在窗口、iframe 之间发送数据...

    <html>
    <head>
      <meta charset="utf-8">
      <title>Callback</title>
      <script>
        window.opener.postMessage({ token: "{{ $token }}", name: "{{ $name }}" }, "YOUR DOMAIN");
        window.close();
      </script>
    </head>
    <body>
    </body>
    </html>
    

    最后这是我在 vue 应用中登录组件的逻辑:

    export default {
            // Waiting for the callback.blade.php message... (token and username).
            mounted () {
              window.addEventListener('message', this.onMessage, false)
            },
    
            beforeDestroy () {
              window.removeEventListener('message', this.onMessage)
            },
    
            methods : {
                // This method call the function to launch the popup and makes the request to the controller. 
                loginGoogle () {
                  const newWindow = openWindow('', 'message')
                  axios.post('api/login-google')
                        .then(response => {
                          newWindow.location.href = response.data;
                        })
                        .catch(function (error) {
                          console.error(error);
                        });
                  },
                  // This method save the new token and username
                  onMessage (e) {
                    if (e.origin !== window.origin || !e.data.token) {
                      return
                    }
                    localStorage.setItem('user',e.data.name)
                    localStorage.setItem('jwt',e.data.token)
    
                    this.$router.go('/board')
                  }
            }
        }
    
        // The popup is launched.
    
        function openWindow (url, title, options = {}) {
          if (typeof url === 'object') {
            options = url
            url = ''
          }
    
          options = { url, title, width: 600, height: 720, ...options }
    
          const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : window.screen.left
          const dualScreenTop = window.screenTop !== undefined ? window.screenTop : window.screen.top
          const width = window.innerWidth || document.documentElement.clientWidth || window.screen.width
          const height = window.innerHeight || document.documentElement.clientHeight || window.screen.height
    
          options.left = ((width / 2) - (options.width / 2)) + dualScreenLeft
          options.top = ((height / 2) - (options.height / 2)) + dualScreenTop
    
          const optionsStr = Object.keys(options).reduce((acc, key) => {
            acc.push(`${key}=${options[key]}`)
            return acc
          }, []).join(',')
    
          const newWindow = window.open(url, title, optionsStr)
    
          if (window.focus) {
            newWindow.focus()
          }
    
          return newWindow
        }
    
    </script> 
    

    希望对你有帮助!

    【讨论】:

    • 非常有用,谢谢。只是一个问题:它是否也适用于 facebook 应用程序?例如,如果我有 fb 应用,我不想在 webview 中重新登录。
    猜你喜欢
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 2015-08-20
    • 2016-04-21
    • 2016-06-07
    • 2021-02-10
    • 2016-09-11
    • 1970-01-01
    相关资源
    最近更新 更多