⚡️ How to call an OAuth based API in Vue.js?

frenchcooc

Corentin

Posted on December 4, 2019

⚡️ How to call an OAuth based API in Vue.js?

I'm 99% sure that you've already used an OAuth based API.

  • 👉 If you signed up with your GitHub account on Dev.to, you've used the GitHub API using their implementation of OAuth2.
  • 👉 Every time you sign-in with Google (or Facebook), you are using OAuth2 as well.

OAuth (especially OAuth2) is now everywhere, probably because it's the best authentication framework in terms of user experience (UX). The user clicks on a button, grants permission, and voilà.

But in terms of developer experience (DX), OAuth is... tricky. Especially for beginners. Why? Probably because it introduces a lot of new concepts at once (see comments below).

Today, I'll showcase something that we're proud of at Bearer.sh, Pizzly, which helps with OAuth by focusing exclusively on the DX. I'm not saying that it makes OAuth great again for developers, but you get the idea.

Let's see how it looks like:

Curious about how you can do it on your application? Here's a full guide.

The Vue.js skeleton

To learn how to use an OAuth based API, we need a Vue.js skeleton. And the least that we need is an app that consumes an API endpoint using OAuth2.

As you probably have a GitHub account, we will use that API, but you can easily switch to any other API that uses OAuth2 (Slack, Salesforce, ...) or OAuth1 (Twitter, Trello, ...).

The GitHub API provides a handy endpoint (/user/starred) to list all the repositories that a user has starred. This endpoint accepts authentication, so it looks like a good use case.

Here's how the application will look like:



<!DOCTYPE html>
<html>
  <body>
    <div id="app">
      <main v-if="user">
        <h1>Latest repositories starred</h1>
        <ul>
          <li v-for="repository in repositories">
            <a :href="repository.html_url" target="_blank">{{repository.name}}</a>
          </li>
        </ul>
        <p v-if="repositories.length === 0">Whoa, such empty!</p>
      </main>
      <div v-else>
        <button @click.prevent="connect">Connect to GitHub</button>
      </div>
    </div>

    <!-- Pizzly.js -->
    <script src="https://cdn.jsdelivr.net/npm/pizzly-js@v0.2.7/dist/index.umd.min.js"></script>

    <!-- Vue.js (developement) -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
      var app = new Vue({
        el: '#app',
        data: {
          user: null,
          repositories: []
        }
      })
    </script>
  </body>
</html>


Enter fullscreen mode Exit fullscreen mode

It's a very basic Vue.js application that displays the content of repositories[] when the user variable is set. Otherwise, it asks the user to connect to GitHub.

The authentication code

Here, we gonna use Pizzly, an open-source project that handles OAuth dances, without headaches. It provides a .connect() method that triggers an authentication flow from your frontend, which you can handle with callbacks. No need to create a redirect URI, deal with backend, etc.

Let's see how to update the skeleton above to use with Pizzly:



var app = new Vue({
  el: "#app",
  data: {
    user: null,
    repositories: []
  },
  mounted: function() {
    // Here we initialize Pizzly.
    this.$pizzly = new Pizzly({
      host: "pushtogsheet.herokuapp.com",
      publishableKey: "pope8Qy8qfYyppnHRMgLMpQ8MuEUKDGeyhfGCj"
    });

    // I'm using my own instance of Pizzly which is hosted on Heroku.
    // Create yours for free and in a few clicks by following
    // https://github.com/Bearer/Pizzly#getting-started
  },
  methods: {
    connect: function() {
      // Here, we create a new method
      // that "connect" a user to GitHub
      this.$pizzly
        .integration('github')
        .connect()
        .then(this.connectSuccess)
        .catch(this.connectError);
    },
    connectSuccess: function(data) {
      // On success, we update the user object
      this.user = data.authId;
      console.log('Successfully logged in!')
    },
    connectError: function (err) {
      console.error(err)
      alert("Something went wrong. Look at the logs.")
    }
  }
});


Enter fullscreen mode Exit fullscreen mode

That's it. A few lines of code in your application and you are ready to handle any OAuth based API 💪.

The configuration part

Pizzly is a self-hosted OAuth manager. This means that you need to host it somewhere, for example on Heroku (it takes 30 seconds). Once hosted somewhere, you can access Pizzly's dashboard, which is where you configure your GitHub integration.

Pizzly dashboard

An authenticated API request

Alright, the authentication is only the first step towards consuming the API. We have already spend a few minutes on that part. Let's move back to funny things.

Using the user identity (authId), we can easily make valid requests to the API. Let's add a new method to the Vue.js application to do that:



fetchStarringRepositories: function() {
  this.$pizzly
    .integration('github') // Call the GitHub API,
    .auth(this.user)       // with the authId previously generated,
    .get('/user/starred')  // ...to retrieve starred repositories
    .then(response => response.json()) // Transform response to JSON
    .then((data) => { this.repositories = data })
    .catch(console.error)
}


Enter fullscreen mode Exit fullscreen mode

And voilà!

What's next?

You now know how to authenticate a user towards any OAuth based API using a Vue.js application. If you're a React developer, the same tutorial is available for React.

It's easily adaptable to all the most famous APIs. No need to create backend routes or understand every single concepts of OAuth. Pizzly takes care of that for you (and for the experts, Pizzly automatically refreshes the access_token).

Again, have a look at the CodePen to have a full understanding of the code and share your thoughts/questions in the comments below.

And if you've liked this tutorial, please add a star to Pizzly on GitHub. Here's the link: https://github.com/Bearer/Pizzly.

💖 💪 🙅 🚩
frenchcooc
Corentin

Posted on December 4, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related