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:
First, install Laravel Passport by running the following commands:
bashcomposer require laravel/passport php artisan migrate php artisan passport:install
The passport:install
command will create the necessary database tables and generate encryption keys.
In your AppServiceProvider
(usually located at app/Providers/AppServiceProvider.php
), add the following lines in the boot
method:
phpuse Laravel\Passport\Passport;
public function boot()
{
Passport::routes();
}
This sets up the routes needed for OAuth2 authentication.
In your User
model (usually located at app/User.php
), make sure it uses the Laravel\Passport\HasApiTokens
trait:
phpuse Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
// ...
}
Run the following command to create a new OAuth2 client for your ReactJS app:
bashphp artisan passport:client --password
Take note of the generated client ID and secret.
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:
jsximport 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;
In your Laravel routes file (web.php
or api.php
), use the auth:api
middleware to protect your API routes:
phpRoute::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.