DEV Community

Cover image for ⚡️ How to call an OAuth based API in Vue.js?
Corentin for Bearer

Posted on • Updated on

⚡️ 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.

Top comments (9)

Collapse
 
frenchcooc profile image
Corentin

To explain further my point about why OAuth is hard for developers, dealing with an OAuth based API requires to understand at least 7 concepts:

  1. An OAuth application
  2. Application credentials (aka cliendId/clientSecret)
  3. OAuth-scopes
  4. Redirect URL
  5. Callback URL
  6. access_token
  7. refresh_token (because access token expires)

Only after understanding all of these concepts (and coding them accordingly), a developer will be able to start using the API.

Collapse
 
mburszley profile image
Maximilian Burszley

Don't forget claims and token (usually JWT) decoding, and maybe throw Kerberos in there.

Collapse
 
raymondcamden profile image
Raymond Camden

So so so SO excited that you introduced me to Bearer!

One nit though - when I try to auth with Firefox, the popup window doesn't scroll. You can see a screen shot here: twitter.com/raymondcamden/status/1...

I've seen this with another oauth demo so it may be a Firefox issue.

Collapse
 
frenchcooc profile image
Corentin

Great news! I'm not aware of that Firefox issue 🤔 Will report it internally

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
frenchcooc profile image
Corentin

I've replied directly to your issue on GitHub. Here's the link ;)

Collapse
 
metalmikester profile image
Michel Renaud

Good timing for this article as I've very recently started looking into this for a personal project. So far I've only tried the Vue.js tutorial on Okta. I put this on my reading list and will give it a shot this weekend.

Collapse
 
emmymay profile image
EmmyMay

For some weird reason, the links you included in this article keep returning a 404

Collapse
 
frenchcooc profile image
Corentin

Hi Emmy. I'm so so sorry to read your comments with such a long delay!

The article has been updated accordingly. Bearer.sh has open-sourced what is described in this article into a new project codenamed Pizzly. Go check it out ;)