Integrating Laravel Passport with Vue.js for OAuth2 authentication involves setting up the backend API using Laravel Passport for OAuth2 server functionalities and creating a frontend Vue.js application that communicates with the backend for authentication.
Here's a step-by-step guide:
bashcomposer require laravel/passport
bashphp artisan migrate
bashphp artisan passport:install
In your User
model, include HasApiTokens
trait:
phpuse Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
// ...
}
AuthServiceProvider
:In AuthServiceProvider
(located at app/Providers/AuthServiceProvider.php
), add the Passport routes to the boot
method:
phpuse Laravel\Passport\Passport;
public function boot()
{
$this->registerPolicies();
Passport::routes();
}
bashvue create your-project-name
cd your-project-name
npm install axios vue-router
Create a file src/router/index.js
:
javascriptimport Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [
// Define your routes
]
const router = new VueRouter({
mode: 'history',
routes,
})
export default router
Create components for login, register, and other authentication-related tasks.
Install Axios:
bashnpm install axios
Create a service file (e.g., src/services/authService.js
) for handling authentication API requests:
javascriptimport axios from 'axios';
const API_URL = 'http://your-api-url';
export default {
login(credentials) {
return axios.post(`${API_URL}/oauth/token`, {
grant_type: 'password',
client_id: process.env.VUE_APP_CLIENT_ID,
client_secret: process.env.VUE_APP_CLIENT_SECRET,
username: credentials.email,
password: credentials.password,
scope: '',
});
},
// Add other authentication-related methods
};
Protect your routes using Vue Router guards to ensure authentication:
javascript// Inside src/router/index.js
import authService from '../services/authService';
router.beforeEach((to, from, next) => {
const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
if (requiresAuth && !authService.isAuthenticated()) {
next('/login');
} else {
next();
}
});
Integrate your authentication components into your Vue.js application.
In your Vue.js project, set environment variables for the client ID and client secret.
Create a .env
file in the root of your Vue project:
envVUE_APP_CLIENT_ID=your-client-id VUE_APP_CLIENT_SECRET=your-client-secret
Start both the Laravel backend and Vue.js frontend applications:
bash# Laravel
php artisan serve
# Vue.js
npm run serve
Now, you should be able to navigate to your Vue.js application, perform login, and make authenticated requests to your Laravel API using Laravel Passport for OAuth2 authentication. Adjust the code as needed for your specific use case and authentication flow.