What is the process for verifying your identity with Google OAuth2 in Vue.js?

Being new to vue.js, I have been struggling with a particular issue for days. Despite knowing that there are a few plugins available, such as:

vue-google-auth

and

vue-google-signin-button

and

vue-authenticate

Unfortunately, none of these plugins come with comprehensive documentation, leading my attempts to utilize them to fail. Even after extensive googling, I could not find any tutorials on implementing OAuth2 authentication in vue.js. Any help would be greatly appreciated if someone can provide a complete working example or direct me to some detailed code resources.

Answer №1

Here is a demonstration of how to implement Google sign-in without using any plugins:

index.html

<meta name="google-signin-client_id" content="your-client-id.apps.googleusercontent.com"
/>

<script src="https://apis.google.com/js/platform.js"></script>

App.vue

<template>
  <div v-show="!profile" id="g-signin2"></div>
  <div v-if="profile">
    <pre>{{ profile }}</pre>
    <button @click="signOut">Sign Out</button>
  </div>
</template>

<script>
export default {
  mounted() {
    this.initGoogleAuth();
    this.renderGoogleAuthButton();
  },

  data() {
    return {
      profile: null
    };
  },

  methods: {
    onSignIn(user) {
      const profile = user.getBasicProfile();
      const fullName = profile.getName();
      const email = profile.getEmail();
      const imageUrl = profile.getImageUrl();
      this.profile = { fullName, email, imageUrl };
    },

    signOut() {
      var auth2 = window.gapi.auth2.getAuthInstance();
      auth2.signOut().then(() => {
        console.log("User signed out");
        this.profile = null;
      });
    },

    initGoogleAuth() {
      window.gapi.load("auth2", function () {
        window.gapi.auth2.init();
      });
    },

    renderGoogleAuthButton() {
      window.gapi.signin2.render("g-signin2", {
        onsuccess: this.onSignIn
      });
    }
  }
};
</script>

Answer №2

Below is a practical demonstration utilizing vue-google-oauth2. To incorporate it, follow these steps:

npm i vue-google-oauth2

You then need to integrate the following code snippet into your APP ENTRY file, for example src/main.js

import GAuth from 'vue-google-oauth2'
Vue.use(GAuth, {clientId: 'XXXXXXXX'})

Replace XXXXXXXX with the clientId provided by I assume you have visited this link if you have attempted Google login previously.

Next, create the component below

<template>
  <div>
    <h1>Test</h1>
    <button @click="handleClickGetAuth" :disabled="!isInit">get auth code</button>
    <button @click="handleClickSignIn" v-if="!isSignIn" :disabled="!isInit">signIn</button>
    <button @click="handleClickSignOut" v-if="isSignIn" :disabled="!isInit">signOout</button>
  </div>
</template>
<script>
export default {
  name: 'test',
  data () {
    return {
      isInit: false,
      isSignIn: false
    }
  },

  methods: {
    async handleClickGetAuth() {
      try {
        const authCode = await this.$gAuth.getAuthCode()
        const response = await this.$http.post('http://your-backend-server.com/auth/google', { code: authCode, redirect_uri: 'postmessage' })
      } catch (error) {
        // Handle failure case
      }
    },

    async handleClickSignIn(){
      try {
        const googleUser = await this.$gAuth.signIn()
        console.log('user', googleUser)
        this.isSignIn = this.$gAuth.isAuthorized
      } catch (error) {
        // Handle failure case
        console.error(error);
        return null;
      }
    },

    async handleClickSignOut(){
      try {
        await this.$gAuth.signOut()
        this.isSignIn = this.$gAuth.isAuthorized
      } catch (error) {
        // Handle failure case
      }
    }
  },
  mounted(){
    let that = this
    let checkGauthLoad = setInterval(function(){
      that.isInit = that.$gAuth.isInit
      that.isSignIn = that.$gAuth.isAuthorized
      if(that.isInit) clearInterval(checkGauthLoad)
    }, 1000);
  }
  
}
</script>

Credit goes to

https://github.com/guruahn/vue-google-oauth2/blob/master/sample.html

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Understanding the process of retrieving a data value from HTML in an AngularJS directive

I'm a beginner with Angular and I'm trying to pass some data to my angular directive from the template. <div class="col-md-6" approver-picker="partner.approverPlan.data" data-pickerType="PLAN"></div> I h ...

Execute a JavaScript function repeatedly, with a specified delay incorporated into it

I am currently working on a JavaScript function that cycles through background images within a div. The function works well, but it stops once all the images have been displayed. How can I make it start over again after going through all the images? $(do ...

Stubborn boolean logic that refuses to work together

Seeking guidance on resolving a persistent issue with my website that has been causing me headaches for the past few weeks. This website was created as my capstone project during a recent graduate program, where I unfortunately did not achieve all the desi ...

Printing in Firefox is ineffective, but functions smoothly in alternative browsers

I'm currently working on customizing some content specifically for printing, so I've implemented a hook import { useState } from 'react' const usePrint = () => { const [isPrinting, setIsPrinting] = useState(false) const hand ...

Why React Native's array.map function fails to calculate the sum of a state

I am currently developing a COVID-19 data app for a school project, and I am struggling to sum the total number of tests and positive results from an API. Below is the snippet of code that I am using: function GetDataApi() { if(data !== null) { const ...

What are the essential files needed in Kendo UI Core for a mobile app?

Several months ago, I created a trial Kendo mobile app but now I want to verify it using the most recent version of Kendo UI Core. In my previous project, I referenced the following files: <link href="../styles/kendo.common.min.css" rel="stylesheet" / ...

When no files are uploaded, req.files.upload.length will return zero; however, if more than one file is uploaded, it will return the total number of files. In the

When using this loop, the variable “req.files.upload.length” will return the file count if 0 or more than one files are uploaded. However, it returns the file size if only one file is uploaded. Why does this happen? This is the upload handler: app.po ...

Recursion using Node.js Promises

I'm facing some difficulties while iterating through my Promises and completing my parser code: let startFrom = 0, totalRecords = 10000, doneRecords = 0 const rows = 10 const parserRequests = function () { if (startFrom <= totalRecords) { ...

Struggling to get a package running in Next.js that is functioning perfectly in ReactJS

Link I have integrated the JSME React npm package into my application to utilize the JSME editor. While this package works seamlessly in a ReactJS environment, I am encountering issues when trying to use it in a Next.js project. I am receiving an error mes ...

Display confirmation pop-up when clicking outside of the modal window in Bootstrap

I am currently utilizing AngularJS (1.5.9) and ui-bootstrap in my application. I am looking to display a confirmation popup if the user clicks outside of an already open modal. I have attempted using both controlled exit with $uibModalInstance.close() and ...

Tips for stopping special characters from being copied and pasted into a number field

My goal is to ensure that only numbers can be copied and pasted into the 'number field'. By preventing the copy and paste of characters like 'e', '+', '-', and '.', I can ensure that the number field only c ...

Angular component equipped with knowledge of event emitter output

I have a custom button component: @Component({ selector: "custom-submit-button" template: ` <button (click)="submitClick.emit()" [disabled]="isDisabled"> <ng-content></ng-content> </butto ...

When dynamically adding input data, the serialized array may not successfully pass through Ajax

function SubmitData(){ var postData = $("#xForm").serializeArray(); $.ajax({ type: "POST", url: "mail.php", data: postData, success:function(data){ console.log(data); }, error: function(jqXHR, textStatus, errorThrown ...

Exploring ways to retrieve global variables within a required() file in Node.js

Imagine having 2 files: main.js, and module.js: //main.js const myModule = require('./module'); let A = 'a'; myModule.log(); //module.js module.exports = { log() { console.log(A); } } After trying to call myModule.log, ...

Prompt Angular to deliberately reevaluate the DOM

Is there a method to prompt Angular to reassess the DOM? I am searching for a way to manually trigger Angular to reassess the entire DOM, or even more specifically, a certain ng-controller DOM element. Is it possible to achieve this? ...

Stop opening when v-btn is clicked in v-expansion-panel headers

function handleClick (event) { event.preventDefault() console.log('bar') }, <v-expansion-panel> <v-expansion-panel-content> <div slot="header"> <v-btn icon flat @click="handleClick($event)"><v-icon>ad ...

Troubleshooting Problems with IndexOf in Javascript/Google Apps Script

Although I've found similar questions about the IndexOf function, none of the answers have resolved my specific issue. In my case, I have a large 2D array containing names and ID codes from a spreadsheet, which I read into an array named rIdr in my a ...

Issue encountered when using Material-UI Button's onClick() function: "Uncaught TypeError: Unable to access 'name' property of undefined" error is thrown

I have been facing an issue with a Material UI button that has an OnClick function. Strangely, when I try to click on the button, it doesn't seem to work and instead shows an error message. Could anyone please point out what might be going wrong here ...

Minimize the amount of ajax requests for quick search functionality

Currently, I am in the process of developing an instant search drop down feature for my website. Everything seems to be functioning correctly except for this particular issue. var timeOut; $('#search input[name=\'search\']'). ...

Removing default headers in Axios for a single requestUpdate Axios to exclude default

I am having an issue with retrieving location data from the Google Maps API due to a CORS Policy Error caused by default headers in my bootstrap.js window.axios.defaults.headers.common = { 'X-Requested-With': 'XMLHttpRequest', & ...