Overview
The Password Manager API uses Laravel Sanctum for API token authentication. Sanctum provides a lightweight authentication system for SPAs (single page applications), mobile applications, and simple token-based APIs.How Sanctum Works
Sanctum offers two authentication methods:- API Token Authentication - Simple token-based authentication for third-party API consumers
- SPA Authentication - Cookie-based authentication for first-party single-page applications
Installation
Sanctum is already included in the project dependencies:personal_access_tokens table is created during migration and stores API tokens:
User Model Configuration
TheUser model is already configured with the HasApiTokens trait:
app/Models/User.php
Sanctum Configuration
The Sanctum configuration is located atconfig/sanctum.php:
Stateful Domains
Domains that receive stateful API authentication:config/sanctum.php
Add your frontend domain to
SANCTUM_STATEFUL_DOMAINS in .env for SPA authentication.Token Expiration
By default, tokens do not expire:config/sanctum.php
.env
Authentication Guards
Sanctum uses the web guard by default:config/sanctum.php
Issuing API Tokens
To issue API tokens to users, create an authentication endpoint:routes/api.php
Token Abilities
You can assign specific abilities (permissions) to tokens:Protecting Routes
To secure your API, add theauth:sanctum middleware to protect routes:
routes/api.php
Making Authenticated Requests
Include the API token in theAuthorization header:
Using JavaScript
Using Postman
- Select the Authorization tab
- Choose Bearer Token as the type
- Paste your API token in the Token field
Accessing Authenticated User
In your controllers, access the authenticated user:Token Management
Revoking Tokens
Revoke all tokens for a user:Logout Endpoint
Create a logout endpoint to revoke tokens:routes/api.php
Checking Token Abilities
If you’ve assigned abilities to tokens, check them in your code:CORS Configuration
For cross-origin requests, ensure CORS is properly configured inconfig/cors.php:
config/cors.php
.env with your frontend URL:
Security Best Practices
- Use HTTPS in production - Always transmit tokens over secure connections
- Set token expiration - Configure reasonable expiration times for tokens
- Implement rate limiting - Protect authentication endpoints from brute force attacks
- Rotate tokens - Issue new tokens periodically and revoke old ones
- Validate requests - Always validate incoming request data
- Store tokens securely - Never expose tokens in URLs or client-side code
- Monitor token usage - Track
last_used_atin thepersonal_access_tokenstable
Rate Limiting
Add rate limiting to authentication endpoints:routes/api.php