Setting up Laravel Passport for client credentials grant with a React frontend involves several steps. Here's a general guide to help you achieve this:
Install Passport: Install Laravel Passport by running the following commands in your terminal:
bashcomposer require laravel/passport php artisan migrate php artisan passport:install
Configure Passport in AuthServiceProvider
:
In your AuthServiceProvider
located at app/Providers/AuthServiceProvider.php
, make sure to add the following lines in the boot
method:
phpuse Laravel\Passport\Passport;
Passport::routes();
Passport::enableImplicitGrant();
Create a Client: Create a Passport client for your React frontend by running:
bashphp artisan passport:client --client
Note the generated client ID and secret.
routes/api.php
for the API endpoints you want to secure with Passport.Install Axios: Axios is a popular HTTP client for making API requests in React. Install it using:
bashnpm install axios
Implement Authentication in React: In your React components, you can use Axios to authenticate with your Laravel API using the client credentials grant. Here's a simplified example using React hooks:
jsximport { useState, useEffect } from 'react';
import axios from 'axios';
const YourComponent = () => {
const [accessToken, setAccessToken] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.post(
'http://your-laravel-api.com/oauth/token',
{
grant_type: 'client_credentials',
client_id: 'your-client-id',
client_secret: 'your-client-secret',
scope: '',
}
);
setAccessToken(response.data.access_token);
} catch (error) {
console.error('Error fetching access token:', error);
}
};
fetchData();
}, []);
// Now you can use the accessToken in your API requests
return (
<div>
{/* Your React component content */}
</div>
);
};
export default YourComponent;
Replace 'http://your-laravel-api.com'
, 'your-client-id'
, and 'your-client-secret'
with your actual Laravel API URL, client ID, and client secret.
This is a basic setup, and you may need to adapt it based on your specific requirements and the structure of your Laravel and React applications.