Setting up Laravel Passport for password grant with a React frontend involves several steps. Passport is a Laravel package that provides OAuth2 server implementation, and the password grant is used when you have a secure backend (Laravel) and a trusted frontend (React) that can handle user credentials securely.
Here's a step-by-step guide to setting up Laravel Passport with password grant and integrating it with a React frontend:
Install Passport:
bashcomposer require laravel/passport
Run Migrations:
bashphp artisan migrate
Install Passport clients:
bashphp artisan passport:install
Configure Auth Service Provider:
Add \Laravel\Passport\PassportServiceProvider::class
to the providers array in config/app.php
.
Update auth
configuration:
Set the driver
option of the api
guard to passport
in config/auth.php
:
php'guards' => [
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
Update User Model:
Your User
model should use the HasApiTokens
trait:
phpuse Laravel\Passport\HasApiTokens;
class User extends Authenticatable {
use HasApiTokens, Notifiable;
// ...
}
Create API Routes:
Define routes for API endpoints in routes/api.php
.
Install Axios:
bashnpm install axios
Implement Authentication Service: Create an authentication service to handle login and token retrieval using Axios.
Login Component: Create a login component that sends user credentials to the Laravel backend and retrieves an access token.
Store Token Securely:
Use a secure storage mechanism like localStorage
or sessionStorage
to store the access token on the client side.
Attach Token to Requests: Attach the access token to the headers of your Axios requests for authenticated API calls.
jsx// AuthService.js
import axios from 'axios';
const API_URL = 'http://your-laravel-api-url';
class AuthService {
login(username, password) {
return axios.post(`${API_URL}/oauth/token`, {
grant_type: 'password',
client_id: process.env.MIX_PASSPORT_CLIENT_ID,
client_secret: process.env.MIX_PASSPORT_CLIENT_SECRET,
username,
password,
});
}
}
export default new AuthService();
jsx// LoginComponent.js
import React, { useState } from 'react';
import AuthService from './AuthService';
const LoginComponent = () => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const handleLogin = async () => {
try {
const response = await AuthService.login(username, password);
const accessToken = response.data.access_token;
// Store the accessToken securely (e.g., localStorage)
} catch (error) {
console.error('Login failed', error);
}
};
return (
<div>
<input type="text" value={username} onChange={(e) => setUsername(e.target.value)} />
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
<button onClick={handleLogin}>Login</button>
</div>
);
};
export default LoginComponent;
Remember to replace placeholder values like http://your-laravel-api-url
, process.env.MIX_PASSPORT_CLIENT_ID
, and process.env.MIX_PASSPORT_CLIENT_SECRET
with your actual values.
This is a simplified example, and you may need to handle token expiration, refresh tokens, and other security considerations in a production environment. Always follow best practices for securing user credentials and tokens in your application.