table of content
Table Of Content

    Implement Facebook Login By Laravel Vue (SPA) Socialite

    Share

    Nowadays, social networking is immensely more prevalent in our daily life. Almost everyone has one or many social accounts, such as Facebook and Twitter, the two huge social network giants. I'm sure that you are want to implement Facebook Login or another social login in your system. We usually use it alongside with traditional email and password method. Some designs login form will integrate the social button for that.

    In this article, I will perform mainly as signing in Facebook social. One of the best Laravel package support and optimize building Laravel app is the Laravel Socialite package. You can refer to further information from the official website documentation Laravel socialite and GitHub Laravel socialite.

    I. Install Laravel Socialite

    It was perfect for getting started with Socialite. I'm going to use the composer tool for installing the package. How incredibly easy to install it as you try it. Please use the command line below to set it up and show me your troubles if you encounter comment sections.

    composer require laravel/socialite
    

    Sometimes, this version doesn't support your Laravel environment because it was the latest version. You may search and download its predecessor.

    II. Install Vue Socialite

    There are many plugins or modules to support authentication in the Vue framework. We need to be consistent and easy to configure with Laravel socialite then Vue socialite is the best choice than other plugins. I'm going to use the npm tool for installing the plugin.

    npm install vue-social-auth
    

    There is a vue-axios plugin which is attached alongside vue-socialite when we conduct to implementation. I recommend that you refer to this link and compare vue-axios and axios to see how they work and distinguish.

    npm install --save axios vue-axios
    

    After you have done this installation, we will see some methods supported by the plugin.

    this.$auth.authenticate() {}
    this.$http.post{}
    

    III. Usage

    To start, you need to build a basic Laravel app or use the available app. So my article will target Facebook as a service of choice. All steps are pretty much identical for Twitter or Google and a variety of others.

    1. Firstly, we need to import all of the extra plugins vue-social-auth and vue-axios and configure them inside the app.js file or indicated vue component.

    import VueAxios from 'vue-axios'
    import VueSocialauth from 'vue-social-auth'
    
    ...
    
    Vue.use(VueAxios, axios);
    Vue.use(VueSocialauth, {
        providers: {
            facebook: {
                clientId: '556444891893350',
                client_secret: '4ba2216bbdccd60fe6f4e6854b6037c3',
                redirectUri: 'https://flagtick.com/auth/facebook/callback'
            }
        }
    });
    

    Have you already never tried it out? I will explain clientId and client_secret and redirectUri. If you are a user as typically and never care about this. But if you're a developer and Facebook completely support many things. That is why sign Facebook will be granted and activated until you register your Facebook developer dashboard application. Facebook will supervise and track your application with permission to access user's data.

    2. Register application from Facebook developer

    You need to access this link to register a new application. Some tutorials from the internet might help you to register quickly. Please notice here; you can choose which option you want to implement login and see Build Connected Experiences.

    Go to Settings > Basic; you will get App ID and Client Secret. When you tab Client Secret and visible it, Facebook may show a warning dialog box and force entering the password to show.

    Some other information needs to be added like Privacy policy URL, URL Terms of Service, App Icon and Webpage,...In Add a platform section, you need to add a call backlink after authenticating Facebook.

    3. Establish Sign In with Product.

    Sign In with Facebook is known as a feature that is shown in plugins or products. In the left-hand sidebar, select Products and add product. Then select Facebook Login. Pretty straight forward from there, you'll see all the OAuth options show up.

    After you have already done the manipulations above and then you can now connect your app as usual. Observe the picture above; if you don't use HTTPS and please disable Implement HTTPS in the Install OAuth application section.

    IV. Implement socialite in Vue template

    In the Vue template, create authProvider() method and identify the param that will be passed inside it: Facebook, Google, Github or Twitter.

    <a @click.prevent="authProvider('facebook')" ...">Sign up with Facebook</a>
    

    Implement authProvider() method inside <script></script>.

    methods: {
        authProvider(provider) {
            let self = this;
            this.$auth.authenticate(provider).then(response => {
                self.socialLogin(provider,response)
            }).catch(err => {
                console.log({err:err})
            })
        },
        socialLogin(provider,response) {
            this.$http.post('/social/'+provider, response).then(response => {
                return response.data.token;
            }).catch(err => {
                console.log({err:err})
            })
        }
    }
    

    V. Configure in web.php and handle Facebook login

    We need to add extra routers used and configured to navigate web.php because we have already declared 'auth/facebook/callback' above.

    Route::post('social/{provider}', 'AuthController@social');
    

    A most common question here how we check it? Please type command 'php artisan route:list' and show a list of all routers if you are getting to get the error while performing the command. It might come from AuthController class. You will replace AuthController with your indicated controller, which allows you to handle this logic.

    public function social($provider) {
        $auth = Socialite::driver($provider)->stateless()->user();
        $email = $auth->getEmail();
        $avatar = $auth->getAvatar();
        return response()->json(compact('token', 'avatar'));
    }
    

    VI. Configure services.php and .env file

    Besides the configuration above, we need to configure extra information in the services.php and .env file. That would be very important when using Laravel socialite and ensure that you don't miss and get any troubles.

    'facebook' => [
        'client_id' => env('FACEBOOK_ID','556444891893350'),
        'client_secret' => env('FACEBOOK_SECRET','4ba2216bbdccd60fe6f4e6854b6037c3'),
        'redirect' => env('FACEBOOK_URL','http://flagtick.com/auth/facebook/callback'),
    ],
    

    The .env has contained some necessary configurations, and you must also configure it. That is all that I'm going to show you in this article.

    FACEBOOK_ID=556444891893350
    FACEBOOK_SECRET=4ba2216bbdccd60fe6f4e6854b6037c3
    FACEBOOK_URL=http://flagtick.com/auth/facebook/callback
    

    VII. Encounter some minor issues

    + If you configure client_id instead of using clientId and you may get the issue.

    + If you didn't attach the URL from redirect in A valid OAuth redirect URI field. And then you may encounter this trouble below.

    + When performing call '/social/facebook' post method. You may get this error from response '419 Page Expired Laravel'. It means that you need to add a 'csrf-token' or ignore it.

    Let us choose a case in which we ignore it. You can add '/social/facebook' in VerifyCsrfToken.php class to avoid this issue.

    class VerifyCsrfToken extends Middleware
    {
        /**
         * The URIs that should be excluded from CSRF verification.
         *
         * @var array
         */
        protected $except = [
            '/social/facebook'
        ];
    }
    

    Please leave a comment if you misunderstand or encountered any issues while following my article.

    Flagtick Group
    Flagtick Group The individual is sociable and enjoys making friends, often sharing knowledge across various fields. |1 second ago
    Flagtick Group The individual is sociable and enjoys making friends, often sharing knowledge across various fields. 1 second ago
    You need to login to do this manipulation!