[SECURITY] Token API Harus Expire & Support Rotasi/Revocation#983
Open
pandigresik wants to merge 2 commits intorilis-devfrom
Open
[SECURITY] Token API Harus Expire & Support Rotasi/Revocation#983pandigresik wants to merge 2 commits intorilis-devfrom
pandigresik wants to merge 2 commits intorilis-devfrom
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Perbaikan issue #965
Summary Implementasi API Token Expiration & Refresh Token
OpenKab - Laravel Sanctum Security Enhancement
Tanggal: 12 Maret 2026
Status: ✅ Completed
📋 Daftar Isi
🎯 Latar Belakang & Masalah
Masalah Awal
Token Sanctum bersifat permanent (
expiration=null)Dampak Security
Tidak Ada Refresh Token
Kebutuhan
✅ Solusi yang Diimplementasikan
1. Token Expiration
2. Refresh Token Mechanism
3. Token Metadata Tracking
4. Anomaly Detection
5. Token Management API
⚙️ Perubahan Konfigurasi
config/sanctum.phpSebelum:
'expiration' => null(tidak pernah expired)Sesudah:
'expiration' => 1440(24 jam)config/auth.php.env(Optional - untuk override)🗄️ Database Changes
Migration 1: Add Metadata to Personal Access Tokens
File:
database/migrations/2026_03_12_085615_add_metadata_to_personal_access_tokens_table.phpKolom Baru:
ip_address(string, 45) - IP address saat token dibuatuser_agent(text) - User agent browser/deviceMigration 2: Create Refresh Tokens Table
File:
database/migrations/2026_03_12_100843_create_refresh_tokens_table.phpKolom:
user_id- Foreign key ke users tablerefresh_token- Random string 100 karakteraccess_token_id- Reference ke personal_access_tokensip_address- IP saat refresh token dibuatuser_agent- User agent saat refresh token dibuatexpires_at- Waktu expired (30 hari dari creation)is_revoked- Flag apakah token sudah dicabutrevoked_at- Waktu pencabutanrevoked_reason- Alasan pencabutan ('logout', 'token_refresh', 'security')📦 New Models
app/Models/RefreshToken.phpapp/Models/User.php(Updated)Tambah relasi refreshTokens:
🎮 Controllers Updates
app/Http/Controllers/Api/Auth/AuthController.phpPerubahan pada method
login():Response Login Baru:
{ "message": "Login Success", "access_token": "eyJ0eXAiOiJKV1QiLCJhbGc...", "refresh_token": "random_100_char_string_xyz", "token_type": "Bearer", "expires_in": 86400, "refresh_expires_in": 2592000 }app/Http/Controllers/Api/TokenController.php(New)Endpoints:
index()- List all user tokensshow($tokenId)- Get token detailsrevoke()- Revoke specific tokenrotate()- Rotate token (revoke + create new)revokeAll()- Revoke all except currentrevokeAllIncludingCurrent()- Revoke all tokensContoh method
rotate():app/Http/Controllers/Api/RefreshTokenController.php(New)Endpoints:
refresh()- Refresh access token using refresh tokenrevoke()- Logout single devicerevokeAll()- Logout all devicesMethod
refresh():🛡️ Middleware
app/Http/Middleware/DetectTokenAnomaly.php(New)Fungsi: Deteksi anomali penggunaan token (IP/device berubah)
Logic:
app/Http/Middleware/AuthApiOptional.php(New)Fungsi: Middleware hybrid untuk API yang bisa diakses via session ATAU token
Use Case: Dashboard admin yang mengakses API endpoint
app/Http/Kernel.php(Updated)Tambah middleware aliases:
🛣️ Routes
routes/apiv1.php(Updated)🔌 API Endpoints
Authentication
/api/v1/signin/api/v1/logoutToken Management
/api/v1/tokens/api/v1/tokens/{id}/api/v1/tokens/revoke/api/v1/tokens/rotate/api/v1/tokens/revoke-all/api/v1/tokens/revoke-all-including-currentRefresh Token
/api/v1/refresh-token/refresh/api/v1/refresh-token/revoke/api/v1/refresh-token/revoke-allHybrid Auth (Session OR Token)
/api/v1/identitas/api/v1/identitas/perbarui/{id}Legend:
auth:sanctum🔒 Security Features
1. Token Expiration
sanctum.expirationauth.refresh_token_lifetime2. Refresh Token Security
3. Anomaly Detection
activity_logtable4. Token Management
5. Response Security
{ "message": "Login Success", "access_token": "eyJ0eXAiOiJKV1QiLCJhbGc...", "refresh_token": "random_100_char_string", "token_type": "Bearer", "expires_in": 86400, // Client tahu kapan expired "refresh_expires_in": 2592000 // Client tahu kapan harus login ulang }🧪 Testing
Test Files Created
tests/Feature/TokenManagementTest.php(15 tests) ✅ PASSINGtest_token_expiration_is_configured()test_login_returns_token_with_expiration()test_token_metadata_captured_on_creation()test_list_user_tokens()test_show_token_details()test_revoke_token()test_rotate_token()test_revoke_all_tokens()test_revoke_all_including_current()test_token_expiration_date()test_is_expired_flag()tests/Feature/TokenAnomalyDetectionTest.php(6 tests) ✅ PASSINGtest_middleware_detects_ip_change()test_middleware_detects_user_agent_change()test_middleware_no_anomaly_when_metadata_matches()test_activity_log_created_for_anomaly()test_middleware_works_without_stored_metadata()test_middleware_updates_last_used_at()tests/Feature/RefreshTokenTest.php(4 tests) ⏸️ SKIPPEDTotal: 21 tests passing, 4 tests skipped (need manual testing)
Run Tests
📦 Migration Guide
Step 1: Backup Database
Step 2: Run Migrations
cd /path/to/OpenKab php artisan migrateOutput yang diharapkan:
Step 3: Clear Config Cache
Step 4: Verify Configuration
Step 5: Test Login
Expected Response:
{ "message": "Login Success", "access_token": "...", "refresh_token": "...", "token_type": "Bearer", "expires_in": 86400, "refresh_expires_in": 2592000 }Step 6: Test Refresh Token
📊 Impact Analysis
Admin Dashboard
authmiddleware)SESSION_LIFETIME(120 menit default)auth.apimiddleware (hybrid)API Clients (Mobile/External)
Existing Tokens
🔧 Troubleshooting
Issue: Refresh token tidak bekerja
Check:
Solution: Run migration
Issue: Token tidak expired setelah 24 jam
Check:
php artisan tinker >>> config('sanctum.expiration')Solution: Clear config cache
Issue: Anomaly detection tidak log
Check:
storage/logs/laravel.logSolution: Verify middleware registered
php artisan route:list --path=api/v1/user # Should show middleware: auth:sanctum,token.anomaly📝 Checklist Deployment
php artisan migrate)php artisan config:clear)📚 References