marventhieme/laravel-authorization-logger
Composer 安装命令:
composer require marventhieme/laravel-authorization-logger
包简介
A Laravel package for logging authorization denials with user context, policy information, and configurable drivers (Ray, Database, Log).
README 文档
README
A Laravel package that automatically logs authorization denials (failed Gate::allows() and policy checks) with comprehensive context including user information, policy details, request data, and the referrer URL. Perfect for security auditing, debugging authorization issues, and monitoring unauthorized access attempts.
Features
- Automatic Logging: Hooks into Laravel's Gate system to automatically log all authorization denials
- Rich Context: Captures user, policy, and request information including:
- User ID, IP address, and roles (Spatie Laravel Permission compatible)
- Policy class, method, and ability being checked
- Model class and ID (if applicable)
- Request method, URL, endpoint, route name, and referrer
- Sanitized request body with sensitive field filtering
- Multiple Handlers: Built-in handlers for Ray, Laravel Log, and Database storage
- Flexible Configuration: Fine-tune what gets logged and what gets ignored
- Database Pruning: Automatic cleanup of old logs with configurable retention periods
- Security Focused: Automatically filters sensitive fields like passwords and tokens
- Custom Handlers: Easy to create your own log handlers for any destination
Installation
Install the package via Composer:
composer require marventhieme/laravel-authorization-logger
Database Setup
Publish and run the migrations:
php artisan vendor:publish --tag="laravel-authorization-logger-migrations"
php artisan migrate
This creates an authorization_denials table to store authorization denial logs.
Configuration
Publish the config file:
php artisan vendor:publish --tag="laravel-authorization-logger-config"
This will create config/authorization-logger.php with the following options:
return [ // Enable/disable logging globally 'enabled' => env('AUTHORIZATION_LOGGING_ENABLED', true), // Log handlers pipeline - data flows through each handler 'handlers' => [ \MarvenThieme\LaravelAuthorizationLogger\Handlers\DebugToRay::class, \MarvenThieme\LaravelAuthorizationLogger\Handlers\WriteToDatabase::class, // \MarvenThieme\LaravelAuthorizationLogger\Handlers\WriteToLog::class, ], // HTTP methods to skip logging (e.g., ['GET', 'HEAD']) 'http_methods_to_ignore' => [], // Classes to ignore in the stack trace 'classes_to_ignore' => [ \Illuminate\Http\Resources\Json\JsonResource::class, ], // Sensitive fields filtered from request bodies 'sensitive_fields' => [ 'password', 'password_confirmation', 'token', 'api_token', 'secret', 'private_key', 'card_number', 'cvv', 'ssn', // ... see config file for full list ], // Maximum request body size in bytes 'max_body_size' => env('AUTHORIZATION_LOGGING_MAX_BODY_SIZE', 10240), // Log channel for WriteToLog handler 'log_channel' => env('AUTHORIZATION_LOGGING_CHANNEL', 'daily'), 'database' => [ // Days to keep logs before pruning 'prunable_after_days' => env('AUTHORIZATION_LOGGING_PRUNABLE_AFTER_DAYS', 30), ], ];
Usage
Once installed, the package works automatically. Any authorization denial will be logged according to your configuration.
Example Scenarios
Policy denial:
// In your controller $this->authorize('update', $post); // Fails if user can't update // Automatically logs: // - User: ID, IP, roles // - Policy: PostPolicy::update // - Model: App\Models\Post #123 // - Request: POST /posts/123, referrer, body
Gate denial:
Gate::authorize('admin-only-feature'); // Fails for non-admins // Automatically logs: // - User: ID, IP, roles // - Ability: admin-only-feature // - Request: Current request context
Available Handlers
DebugToRay
Sends authorization denials to Ray for real-time debugging.
'handlers' => [ \MarvenThieme\LaravelAuthorizationLogger\Handlers\DebugToRay::class, ],
WriteToDatabase
Stores denials in the authorization_denials table.
'handlers' => [ \MarvenThieme\LaravelAuthorizationLogger\Handlers\WriteToDatabase::class, ],
Query the database:
use MarvenThieme\LaravelAuthorizationLogger\Models\AuthorizationDenial; // Recent denials for a user $denials = AuthorizationDenial::where('user_id', $userId) ->orderBy('logged_at', 'desc') ->get(); // Denials for a specific ability $denials = AuthorizationDenial::where('ability', 'update') ->where('model_class', Post::class) ->get();
WriteToLog
Writes denials to Laravel's log system.
'handlers' => [ \MarvenThieme\LaravelAuthorizationLogger\Handlers\WriteToLog::class, ],
Configure the log channel:
'log_channel' => env('AUTHORIZATION_LOGGING_CHANNEL', 'daily'),
Creating Custom Handlers
Create your own handler by implementing the LogHandler contract:
namespace App\Handlers; use MarvenThieme\LaravelAuthorizationLogger\Contracts\LogHandler; use MarvenThieme\LaravelAuthorizationLogger\Objects\LogData; class SendToSlack implements LogHandler { public function handle(LogData $logData): void { // Send to Slack, email, external API, etc. // Access data: $logData->userContext, $logData->policyContext, $logData->requestContext } }
Register it in config:
'handlers' => [ \App\Handlers\SendToSlack::class, ],
LogData Structure
The LogData object passed to handlers contains:
// Event info $logData->event; // "Authorization Denied" $logData->timestamp; // ISO8601 timestamp // User context $logData->userContext->type; // "authenticated" or "anonymous" $logData->userContext->userId; // User ID or null $logData->userContext->ipAddress; // IP address $logData->userContext->roles; // Array of role names (if using Spatie Permission) // Policy context $logData->policyContext->ability; // "update", "delete", etc. $logData->policyContext->policyClass; // "App\Policies\PostPolicy" $logData->policyContext->policyMethod; // "update" $logData->policyContext->modelClass; // "App\Models\Post" $logData->policyContext->modelId; // 123 // Request context $logData->requestContext->method; // "POST" $logData->requestContext->url; // "https://example.com/posts/123" $logData->requestContext->endpoint; // "/posts/123" $logData->requestContext->routeName; // "posts.update" $logData->requestContext->referrer; // Previous URL or null $logData->requestContext->body; // Sanitized request body
Database Pruning
The package uses Laravel's model pruning to automatically clean up old logs. Configure retention in your config:
'database' => [ 'prunable_after_days' => env('AUTHORIZATION_LOGGING_PRUNABLE_AFTER_DAYS', 30), ],
Schedule the pruning command in app/Console/Kernel.php:
protected function schedule(Schedule $schedule) { $schedule->command('model:prune')->daily(); }
Advanced Configuration
Ignoring Specific HTTP Methods
Skip logging for GET requests (useful for reducing noise from UI checks):
'http_methods_to_ignore' => ['GET', 'HEAD'],
Ignoring Specific Classes
By default, authorization checks from JSON Resources are ignored:
'classes_to_ignore' => [ \Illuminate\Http\Resources\Json\JsonResource::class, // Add your own classes here ],
Custom Sensitive Fields
Add your own fields to filter from request bodies:
'sensitive_fields' => [ 'password', 'api_key', 'your_custom_secret_field', ],
Environment Variables
Available environment variables for quick configuration:
AUTHORIZATION_LOGGING_ENABLED=true AUTHORIZATION_LOGGING_MAX_BODY_SIZE=10240 AUTHORIZATION_LOGGING_CHANNEL=daily AUTHORIZATION_LOGGING_PRUNABLE_AFTER_DAYS=30
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
License
The MIT License (MIT). Please see License File for more information.
marventhieme/laravel-authorization-logger 适用场景与选型建议
marventhieme/laravel-authorization-logger 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 192 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 12 月 01 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「laravel」 「Marven Thieme」 「laravel-authorization-logger」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 marventhieme/laravel-authorization-logger 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 marventhieme/laravel-authorization-logger 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 marventhieme/laravel-authorization-logger 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Alfabank REST API integration
Laravel package for Accurate Online API integration.
Shared RCX Laravel DataTables UI and configuration helpers.
Boot a Laravel project on any machine with one command: app:serve installs missing tools (PHP, Node, Composer, Herd, Docker), creates .env, sets up the database, runs migrations, builds assets, starts a queue worker and serves via Herd, Sail or artisan serve; app:down cleanly stops everything it sta
Branded, diagnostic error pages (500, 403, 404, 419, 503) for Filament — native Filament UI, dark mode and translations out of the box.
Turn any PDF into a Pingen-ready A4 letter (generated address cover page + A4 normalisation + safe margins) and send it through the Pingen print & mail API. Laravel-first.
统计信息
- 总下载量: 192
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 27
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-12-01