API Security
XinAdmin builds a complete API security system through middleware chains, annotation routing, request validation, and exception handling.
Route Middleware
All protected API routes use triple middleware:
AnnoRoute Annotation Routing
XinAdmin provides an AnnoRoute annotation routing system that auto-registers routes and permission middleware via PHP 8 attributes, avoiding manual route definition and middleware configuration:
Annotation Parameters
RouteRegisterService scans all annotated controllers on boot, automatically calling Laravel route registration with ['auth:sanctum', 'authGuard', 'abilities:{prefix}.{authorize}'] middleware attached.
Unauthorized Access Handling
When a user's token lacks the required permission, ExceptionsHandler catches MissingAbilityException and returns:
Other security-related exception handling:
CORS Security
Global CORS middleware AllowCrossDomainMiddleware:
OPTIONS preflight requests receive a 204 status code. CORS headers are also duplicated in the exception handler as a safety net.
Request Validation
All form requests extend BaseFormRequest, providing unified validation rules:
Validation failure response:
Adding a Protected API Endpoint
Steps to add a new protected endpoint to the system:
1. Add a permission rule record
Insert a new record in sys_rule with type=rule and the corresponding permission key, e.g., my.module.action.
2. Define the route with middleware
3. Add frontend permission control