To authenticate API requests between Laravel and Node.js, you can use JSON Web Tokens (JWT) for token-based authentication. Here's a step-by-step guide:
Step 1: Generate JWT Tokens in Laravel
1. Install Laravel Passport:
- Run the following command in your terminal to install Laravel Passport:
bash
composer require laravel/passport
2. Configure Passport:
- Run the following command to publish the Passport configuration:
bash
php artisan vendor:publish --provider="Laravel\Passport\PassportServiceProvider"
3. Generate JWT Tokens:
- In your Laravel controller, use the `createToken` method to generate a JWT token for a user:
php
use App\User;
use Illuminate\Support\Facades\Hash;
use Laravel\Passport\TokenRepositoryInterface;
use Laravel\Passport\Token;
public function login(Request $request)
{
$user = User::where('email', $request->input('email'))->first();
if (!$user || !Hash::check($request->input('password'), $user->password)) {
return response()->json(['error' => 'Invalid credentials'], 401);
}
$token = $user->createToken('token-name')->plainTextToken;
return response()->json(['token' => $token]);
}
Step 2: Use JWT Tokens in Node.js
1. Send JWT Tokens with Requests:
- In your Node.js application, include the JWT token in the headers of each request to your Laravel API:
javascript
axios.get('/api/items', {
headers: {
'Authorization': 'Bearer ' + token,
},
});
2. Validate JWT Tokens in Laravel:
- In your Laravel API controller, validate the JWT token in the request headers:
php
public function index(Request $request)
{
if (!$request->hasValidCsrfToken()) {
return response()->json(['error' => 'CSRF token mismatch'], 419);
}
// Process the request
}
Conclusion
By following these steps, you can effectively authenticate API requests between Laravel and Node.js using JWT tokens. This ensures that only authorized users can access protected resources and perform certain actions.
Citations:[1] https://dotdev.co/authenticate-laravel-5-user-account-in-nodejs-socket-io-using-json-web-tokens-jwt-f74009d612f8
[2] https://laracasts.com/discuss/channels/laravel/nodejs-call-to-laravel-api
[3] https://stackoverflow.com/questions/44178418/laravel-authentication-for-node-js-app
[4] https://www.linkedin.com/pulse/implementing-authentication-authorization-laravel-api-durim-gjoshi
[5] https://stackoverflow.com/questions/48235260/node-js-access-to-api-laravel