The easiest way to authenticate users with Vue.js
Tags: vue, oauth, authentication, kobble
Published: 2024-04-05 23:13:42

## Introduction

A wise man once said:

> The easiest way to code authentication is not to code it.

Well, maybe I was that man. But as a matter of fact, it's true.


## The result (in 10 minutes)

First, here's what we're going to build:

[Demo Page](https://vue-auth-example.vercel.app)


![Screenshot of the result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rwbsbb1x5pnz5msozn3h.png)



As you can see, it's a simple Single Page Application built with [Vue.js](https://vuejs.org/) where our users can sign up / sign in with a few clicks.

Once logged in, we can access various methods to fetch the user's profile, user's access token and more.

## Only 10 minutes? What's the catch?

There is no catch. In this tutorial, we're going to use [Kobble.io](https://kobble.io). This service provides a full-featured customer portal as a service that you can use from any website.

This portal includes authentication, monetization, rate-limiting, and more advanced features.

**TL;DR: We'll save hours of tedious work by implementing their Auth SPA SDK with a few lines of code.**

## Create an application on Kobble

- Sign in for free at [Kobble](https://kobble.io)
- Create a new Project
- Go to [Applications](https://app.kobble.io/p/applications) and create an application
- In the Redirect URI section, add **http://localhost:3000/callback** 

> The callback URL must match your Vue.js app. We'll create that callback page later on.


![Creating a Kobble Application](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tz7t9kkjdu1xa978rsfz.png)


## Select your authentication providers

[Kobble](https://kobble.io) has already created a customer portal for us. But now, we need to activate the authentication providers we want.

- Go to [Authentication](https://app.kobble.io/p/authentication) and activate the providers of your choice (it's straightforward, but you can read [their docs](https://docs.kobble.io/product/authentication/overview) if needed).
- That's it.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8gbajw4r0osefjhvk0vh.png)


If you've configured everything correctly, your customer portal should be up and running already at **https://[your-project].portal.kobble.io** and you can customize it on the [Customer Portal](https://app.kobble.io/p/portal/branding) section of your dashboard.


## Setting up your Vue.js app

### Quick note
Here I'm assuming you already have a Vue.JS app up and running. If you don't the easiest way to get started is probably to use a [Vite](https://vitejs.dev/guide/) template by running:

```bash
npm create vite@latest my-vue-app -- --template vue-ts
```

### Install Kobble SDK

In your terminal, run the following command:

```bash
npm i -S @kobbleio/auth-spa-js
```

Then, create a file to init the SDK:

```typescript
// src/kobble/index.ts

import { createKobbleClient } from '@kobbleio/auth-spa-js'

export const kobbleClient = createKobbleClient({
  domain: import.meta.env.VITE_KOBBLE_DOMAIN,
  clientId: import.meta.env.VITE_KOBBLE_CLIENT_ID,
  redirectUri: import.meta.env.VITE_KOBBLE_REDIRECT_URI
})
```

Replace the environment variables with the values provided in the Kobble Application we created earlier.

![Kobble Application Screenshot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/be30lgejsvy05rf66g5e.png)


### Implement the login

The OAuth flow will work as follows:

1. the user clicks on a login button
2. he's redirected to your customer portal
3. once logged-in he's redirected back to your callback URL to complete the OAuth flow

Kobble provides everything we need to handle this.

#### Handle login

To handle login, you only have to use the `loginWithRedirect()` method provided by our Kobble instance.

You just have to create a button anywhere on your app that looks like this:

```vuejs
<script lang="ts">
// We import the kobbleClient we init before
import { kobbleClient } from '@/kobble';

const login = () => {
   kobbleClient.loginWithRedirect();
};
</script>

<template>
    <button @click="login">Login</button>
</template>
```

#### Handle the callback

To make sure our flow can be completed, let's create a callback page and use the **handleRedirectCallback()** method.


```vuejs
<script lang="ts">
import { kobbleClient } from '@/kobble'

export default {
  async mounted() {
    try {
      await kobbleClient.handleRedirectCallback()
      this.$router.replace({ name: 'home' })
    } catch (e: any) {
      console.log('Error while authenticating', e.message)
    }
  }
}
</script>

<template>
  <div>
    <h1>Authenticating...</h1>
  </div>
</template>
```

> Make sure your callback page URL matches the Redirect URI you previously used.


#### Listen to the user state changes

That's it. Your vue.js app is ready to authenticate your users.

Now, you can listen to the user's state using the following method:

```typescript
/**
 * This callback is triggered every time the user object changes:
 * - on login
 * - on logout
 * - on access token refreshed
 */
kobbleClient.onAuthStateChanged((data) => {
  console.log('User', data.user)
})

```

#### Other methods

The Kobble client also exposes a lot of utility functions, such as:

- logout()
- getIdToken()
- getAccessToken()


## Conclusion

In under 10 minutes, we added authentication to our vuejs application using [Kobble.io](https://kobble.io).


**Demo website:**

https://vue-auth-example.vercel.app

**Full Code**:

https://github.com/kobble-io/vue-auth-example


## Thank you!
If you liked this tutorial, feel free to smash the like button and react in the comments below :)