🎉 Enjoying this package? Consider sponsoring me on GitHub or buying me a beer.
Webhooks
The package can send webhooks to external services when authentication events occur.
Configuration
Configure webhooks in your config/authentication-log.php:
1'webhooks' => [ 2 [ 3 'url' => 'https://example.com/webhook', 4 'events' => ['login', 'failed', 'new_device', 'suspicious'], 5 'headers' => [ 6 'Authorization' => 'Bearer your-token', 7 'X-Custom-Header' => 'value', 8 ], 9 ],10 [11 'url' => 'https://another-service.com/webhook',12 'events' => ['*'], // Listen to all events13 'headers' => [14 'Authorization' => 'Bearer another-token',15 ],16 ],17],
Available Events
login- Fired when a user successfully logs infailed- Fired when a login attempt failsnew_device- Fired when a user logs in from a new devicesuspicious- Fired when suspicious activity is detected
Use ['*'] to listen to all events.
Webhook Payload
Each webhook sends a JSON payload with the following structure:
1{ 2 "event": "login", 3 "timestamp": "2024-01-15T10:30:00+00:00", 4 "user": { 5 "id": 1, 7 }, 8 "authentication_log": { 9 "id": 123,10 "ip_address": "192.168.1.1",11 "user_agent": "Mozilla/5.0...",12 "device_id": "abc123...",13 "device_name": "Chrome on Windows",14 "login_at": "2024-01-15T10:30:00+00:00",15 "login_successful": true,16 "is_suspicious": false,17 "location": {18 "city": "New York",19 "state": "NY",20 "country": "US",21 "country_code": "US"22 }23 }24}
Webhook Settings
Configure webhook behavior:
1'webhook_settings' => [2 'log_failures' => true, // Log failed webhook requests3 'timeout' => 10, // HTTP timeout in seconds4],
Error Handling
Failed webhook requests are automatically logged (if log_failures is enabled). The package will continue processing even if a webhook fails, ensuring authentication logging is not interrupted.
Example: Webhook Receiver
Here's an example of how you might handle webhooks on the receiving end:
1// In your webhook receiver 2Route::post('/webhook', function (Request $request) { 3 $event = $request->input('event'); 4 $user = $request->input('user'); 5 $log = $request->input('authentication_log'); 6 7 switch ($event) { 8 case 'suspicious': 9 // Send alert to security team10 SecurityAlert::create([11 'user_id' => $user['id'],12 'type' => 'suspicious_activity',13 'details' => $log,14 ]);15 break;16 17 case 'new_device':18 // Log new device for audit19 AuditLog::create([20 'user_id' => $user['id'],21 'action' => 'new_device_login',22 'details' => $log,23 ]);24 break;25 }26 27 return response()->json(['status' => 'received']);28})->middleware('auth:sanctum'); // Protect your webhook endpoint
Testing Webhooks
You can test webhooks locally using tools like ngrok or webhook.site:
- Set up a public URL using ngrok or webhook.site
- Add it to your webhook configuration
- Trigger authentication events
- Check the webhook receiver for payloads