To implement machine-to-machine authentication in Laravel, you can use the Laravel Passport package. Here are the steps to follow:
- Install Laravel Passport by running the following command in your terminal:
composer require laravel/passport
- Run the migration to create the necessary tables:
php artisan migrate
- In your
AuthServiceProvider, add the following lines to thebootmethod:
Passport::routes();
Passport::enableImplicitGrant();
- In your
Usermodel, add theHasApiTokenstrait:
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
...
}
- Create a client by running the following command:
php artisan passport:client --client
This will create a new client and display the client ID and secret. Make sure to save these values as you will need them to authenticate.
- To authenticate, you can use the following code:
$response = Http::asForm()->post('http://your-app.com/oauth/token', [
'grant_type' => 'client_credentials',
'client_id' => 'your-client-id',
'client_secret' => 'your-client-secret',
'scope' => '',
]);
$accessToken = $response->json()['access_token'];
Make sure to replace your-app.com, your-client-id, and your-client-secret with the appropriate values.
- Finally, you can use the access token to make API requests:
$response = Http::withToken($accessToken)->get('http://your-app.com/api/user');
Make sure to replace http://your-app.com/api/user with the appropriate API endpoint.
That's it! You should now be able to authenticate and make API requests using machine-to-machine authentication.