How to use Laravel Passport for API authentication with ReactJS



Image not found!!

Laravel Passport is a full OAuth2 server implementation for Laravel, which makes it easy to set up API authentication in your Laravel application. When integrating it with a ReactJS frontend, you'll typically use OAuth2's "Authorization Code" grant type for secure authentication. Here's a step-by-step guide on how to set this up:

1. Install Laravel Passport

First, install Laravel Passport by running the following commands:

bash
composer require laravel/passport php artisan migrate php artisan passport:install

The passport:install command will create the necessary database tables and generate encryption keys.

2. Configure Laravel Passport

In your AppServiceProvider (usually located at app/Providers/AppServiceProvider.php), add the following lines in the boot method:

php
use Laravel\Passport\Passport; public function boot() { Passport::routes(); }

This sets up the routes needed for OAuth2 authentication.

3. Configure the User Model

In your User model (usually located at app/User.php), make sure it uses the Laravel\Passport\HasApiTokens trait:

php
use Laravel\Passport\HasApiTokens; class User extends Authenticatable { use HasApiTokens, Notifiable; // ... }

4. Create OAuth2 Clients

Run the following command to create a new OAuth2 client for your ReactJS app:

bash
php artisan passport:client --password

Take note of the generated client ID and secret.

5. Set Up the ReactJS App

In your ReactJS app, you'll need to handle the authentication flow. You can use a library like axios for HTTP requests and react-router-dom for routing.

Here's a simplified example:

jsx
import React, { useState } from 'react'; import axios from 'axios'; const Login = () => { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const handleLogin = async () => { try { const response = await axios.post('/oauth/token', { grant_type: 'password', client_id: 'your-client-id', client_secret: 'your-client-secret', username: email, password: password, scope: '', }); // Store the access token in your app's state or localStorage const accessToken = response.data.access_token; // ... } catch (error) { console.error('Login failed:', error); } }; return ( <div> <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} /> <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} /> <button onClick={handleLogin}>Login</button> </div> ); }; export default Login;

6. Protect Your Routes

In your Laravel routes file (web.php or api.php), use the auth:api middleware to protect your API routes:

php
Route::middleware('auth:api')->group(function () { // Your protected routes go here });

Now, your Laravel API is protected, and only authenticated users can access the protected routes.

This is a basic example, and you might want to implement features like token refresh, logout, error handling, etc. Make sure to consult the Laravel Passport documentation for more details: Laravel Passport Documentation.