Google Calendar API Post Request missing authentication credentials

Viewed 21

I'm pretty new to coding and am attempting to implement OAuth in order to allow users to add events to their google calendar directly from my VueJS application. I am following the Google Identity Services JavaScript implicit model (https://developers.google.com/identity/oauth2/web/guides/use-token-model) to generate a token and make a REST request to the calendar API.

I've been able to generate a token, which works perfectly with a 'get' request to return all events on a users calendar.

My issue is that when I try to run a 'post' request, I receive a 401 unauthorized error: message: "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential".

I have tried revoking my token and obtaining a new one. I've also verified through the google cloud developer platform that my app has the required scopes added and have tried using both the 'https://www.googleapis.com/auth/calendar' and 'https://www.googleapis.com/auth/calendar.events' scopes required as per the Calendar API documentation for creating an event(https://developers.google.com/calendar/api/v3/reference/events/insert).

I can try pivoting to use the Google JavaScript client library to make the request, however I would really like to figure out how to do this through a post request (and understand why my current attempts aren't working).

Any help would be significantly appreciated. Code below:

methods: {
    initClient: function () {
      this.client = google.accounts.oauth2.initTokenClient({
        client_id: this.clientID,
        scope: 'https://www.googleapis.com/auth/calendar.events',
        callback: (tokenResponse) => {
          this.access_token = tokenResponse.access_token;
        },
      });
    },
    getToken: function () {
      this.client.requestAccessToken()
    },
    getCalendar: function () {
      axios.get('https://www.googleapis.com/calendar/v3/calendars/primary/events/', { 
        headers: { 'Authorization': `Bearer ${this.access_token}` }
      }).then(response => {
        console.log(response)
      }).catch(error => {
        console.log(error.response.data.error)
      })
    },
    addEventToCalendar: function () {
      axios.post('https://www.googleapis.com/calendar/v3/calendars/primary/events/', {
        headers: { 'Authorization': `Bearer ${this.access_token}` }
      }, this.event).then(response => {
        console.log(response)
      }).catch(error => {
        console.log(error.response.data.error)
      })
    },

Thank you!

0 Answers
Related