承接 marventhieme/laravel-authorization-logger 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

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

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

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 我们能提供哪些服务?
定制开发 / 二次开发

基于 marventhieme/laravel-authorization-logger 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 192
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 27
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-12-01