Skip to main content
UnauthorizedException is used when authentication is required or permissions are insufficient. It returns HTTP 401 status code and is used for situations like login required, session expired, or insufficient permissions.

Basic Usage

Simple Example:

Practical Examples

Basic Authentication Check

For simple login checks, using Guards is cleaner:

Resource Ownership Validation

Role-Based Permission Validation

Complex Permission Validation

Organization/Team Permission Validation

API Key Authentication

Time-Based Access Control

IP-Based Access Control

Guards vs Manual Check Comparison

Manual Check (Complex Logic)

payload Usage Patterns

Login Prompt

Permission Upgrade Prompt

Expiration Information

Client Response Examples

Basic Response

Response with payload

401 vs 403

  • 401 Unauthorized: When authentication itself fails or permissions are insufficient
  • 403 Forbidden: When authenticated but explicitly lacks permission to access the resource
In Sonamu, UnauthorizedException handles both, but you can create a custom ForbiddenException if needed.