paint-brush
Connecting Vue.js with OAuth Based APIby@frenchcooc
1,337 reads
1,337 reads

Connecting Vue.js with OAuth Based API

by Corentin BrossaultAugust 21st, 2020
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Pizzly is an open-source project that handles OAuth dances, without headaches. It provides an authentication flow from your frontend using OAuth2 or OAuth1. It's a basic Vue.js application that displays the content of repositories when the user variable is set. We will use the GitHub API to list all the repositories that a user has starred. We need a Vue.js skeleton to learn how to use an OAuth based API, we need to create a. user to connect to GitHub.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail

Coin Mentioned

Mention Thumbnail
featured image - Connecting Vue.js with OAuth Based API
Corentin Brossault HackerNoon profile picture

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

> 👉 If you signed up with your GitHub account on Hackernoon, you've used the GitHub API using their implementation of OAuth2. Every time you sign-in with Google (or Facebook) on a website, 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/[email protected]/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>

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 part

As said, 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. No need to deal with a backend, it's fully handled from the front.

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.")
    }
  }
});

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.

And voilà!

What's next?

You now know how to authenticate a user towards any OAuth based API using a Vue.js application.

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 👇

Previously published at https://dev.to/bearer/how-to-use-an-oauth-based-api-in-vue-js-1elo