Share this:

As web applications grow and evolve, securing your API with OAuth2 becomes increasingly important to maintain the safety and integrity of user data. In this comprehensive guide, we will explore how to achieve this security by integrating Laravel Passport, a powerful OAuth2 server, with a Vue.js frontend. We’ll walk you through the process step by step, ensuring that your API remains protected and accessible only to authorized users.

Laravel Passport is a powerful OAuth2 server that simplifies API authentication for your web applications. When combined with the flexibility and reactivity of Vue.js, it provides a robust and secure solution for managing user authentication and API access. In this detailed guide, we will walk you through the process of setting up Laravel Passport and integrating it with a Vue.js frontend, ensuring the security of your API using OAuth2.

Prerequisites

Before you begin, make sure you have the following installed and set up:

  1. PHP >= 7.3
  2. Laravel >= 8.x
  3. Composer, the PHP package manager
  4. Node.js and npm
  5. Vue.js 2.x or 3.x

Step 1: Install Laravel Passport

First, navigate to your Laravel project directory and install Laravel Passport using Composer:

composer require laravel/passport

After the installation is complete, run the following commands to publish the Passport migrations and configuration file:

php artisan vendor:publish --tag=passport-config
php artisan vendor:publish --tag=passport-migrations

Now, run the migrations to create the necessary database tables:

php artisan migrate

Finally, add the Laravel\Passport\HasApiTokens trait to your User model:

use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
}

Step 2: Configure Passport

In your config/auth.php file, set the api guard’s driver to passport:

'guards' => [
    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
],

Next, run the following command to install the Passport encryption keys:

php artisan passport:install

Step 3: Set Up OAuth2 Routes and Controllers

In your routes/api.php file, add the following routes for handling OAuth2 authorization and token requests:

use Laravel\Passport\Http\Controllers\AccessTokenController;
use Laravel\Passport\Http\Controllers\ApproveAuthorizationController;
use Laravel\Passport\Http\Controllers\DenyAuthorizationController;
use Psr\Http\Message\ServerRequestInterface;

Route::post('oauth/authorize', [ApproveAuthorizationController::class, 'approve']);
Route::delete('oauth/authorize', [DenyAuthorizationController::class, 'deny']);
Route::post('oauth/token', [AccessTokenController::class, 'issueToken'])->middleware('throttle');

Step 4: Set Up Vue.js Frontend

If you haven’t already, set up Vue.js in your Laravel project using Laravel Mix:

npm install vue

Create a new Vue component called Login.vue in your resources/js/components directory. This component will handle user login and request an access token from the Laravel Passport server:

<template>
  <div>
    <form @submit.prevent="login">
      <input type="text" v-model="email" placeholder="Email">
      <input type="password" v-model="password" placeholder="Password">
      <button type="submit">Login</button>
    </form>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      email: '',
      password: '',
    };
  },
  methods: {
    async login() {
      try {
        const response = await axios.post('/oauth/token', {
          grant_type: 'password',
          client_id: '<YOUR_CLIENT_ID>',
         client_secret: '<YOUR_CLIENT_SECRET>',
         username: this.email,
         password: this.password,
      });
      localStorage.setItem('access_token', response.data.access_token);
        this.$emit('authenticated');
      } catch (error) {
        console.error('Authentication failed:', error);
      }
    },
  },
};
</script>

Replace <YOUR_CLIENT_ID> and <YOUR_CLIENT_SECRET> with the appropriate values from the output of the php artisan passport:install command.

Step 5: Create a Vue.js Router Guard

To protect your routes from unauthorized access, create a Vue.js router guard. In your router.js file, add the following code:

import Vue from 'vue';
import VueRouter from 'vue-router';
import store from './store';

Vue.use(VueRouter);

const routes = [
  // Your routes configuration
];

const router = new VueRouter({
  routes,
});

router.beforeEach((to, from, next) => {
  if (to.matched.some((record) => record.meta.requiresAuth)) {
    if (!store.getters.isAuthenticated) {
      next({ name: 'login' });
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router;

Now, you can add the meta: { requiresAuth: true } property to any route that requires authentication.

Step 6: Use Axios to Make API Requests

Install Axios, a popular HTTP client library, to make API requests from your Vue.js components:

npm install axios

In your main.js file, configure Axios to include the access token in the Authorization header for all requests:

import axios from 'axios';

axios.interceptors.request.use((config) => {
  const token = localStorage.getItem('access_token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

Vue.prototype.$http = axios;

Now, you can use this.$http in your Vue components to make authenticated API requests.

Conclusion

You have now successfully secured your Laravel API using OAuth2 with Laravel Passport and integrated it with a Vue.js frontend. This setup provides a robust and secure authentication system for your web application, ensuring that only authorized users can access protected resources. Enjoy the added security and flexibility this combination brings to your projects!

Share this:

Categorized in: