Files
next-go-blog/CORS_API_DOCUMENTATION.md
Beyhan Oğur 6d95e27114 first commit
2026-04-26 22:16:43 +03:00

621 lines
14 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# CORS Whitelist & Blacklist API Dokümantasyonu
## 📋 Genel Bakış
AuthCentral'da CORS (Cross-Origin Resource Sharing) yönetimi için Whitelist ve Blacklist sistemleri mevcuttur.
### Özellikler:
- ✅ CRUD operasyonları (Create, Read, Update, Delete)
- ✅ Redis cache desteği
- ✅ Admin only endpoints
- ✅ Active/Inactive durumları
- ✅ Audit trail (created_by, updated_by)
---
## 🔐 Authentication
Tüm endpoint'ler **Admin** yetkisi gerektirir:
```
Authorization: Bearer {admin_access_token}
```
---
## 📡 CORS Whitelist API
### 1. Tüm Whitelist Kayıtlarını Listele
```http
GET /v1/settings/cors/whitelist
```
**Headers:**
```
Authorization: Bearer {token}
```
**Yanıt:**
```json
[
{
"id": "uuid",
"origin": "http://localhost:3000",
"description": "Development frontend",
"is_active": true,
"created_by": "admin@gauth.local",
"created_at": "2026-02-05T10:00:00Z",
"updated_at": "2026-02-05T10:00:00Z"
},
{
"id": "uuid",
"origin": "https://myapp.com",
"description": "Production frontend",
"is_active": true,
"created_by": "admin@gauth.local",
"created_at": "2026-02-05T09:00:00Z",
"updated_at": "2026-02-05T09:00:00Z"
}
]
```
### 2. Whitelist Kaydı Oluştur
```http
POST /v1/settings/cors/whitelist
```
**Headers:**
```
Authorization: Bearer {token}
Content-Type: application/json
```
**Body:**
```json
{
"origin": "https://example.com",
"description": "Customer frontend application"
}
```
**Başarılı Yanıt (201):**
```json
{
"id": "new-uuid",
"origin": "https://example.com",
"description": "Customer frontend application",
"is_active": true,
"created_by": "admin@gauth.local",
"created_at": "2026-02-05T11:00:00Z",
"updated_at": "2026-02-05T11:00:00Z"
}
```
### 3. Whitelist Kaydını Güncelle
```http
PUT /v1/settings/cors/whitelist/{id}
```
**Headers:**
```
Authorization: Bearer {token}
Content-Type: application/json
```
**Body (tüm alanlar opsiyonel):**
```json
{
"origin": "https://new-domain.com",
"description": "Updated description",
"is_active": false
}
```
**Başarılı Yanıt (200):**
```json
{
"message": "Whitelist updated successfully"
}
```
### 4. Whitelist Kaydını Sil
```http
DELETE /v1/settings/cors/whitelist/{id}
```
**Headers:**
```
Authorization: Bearer {token}
```
**Başarılı Yanıt (200):**
```json
{
"message": "Whitelist entry deleted successfully"
}
```
---
## 🚫 CORS Blacklist API
### 1. Tüm Blacklist Kayıtlarını Listele
```http
GET /v1/settings/cors/blacklist
```
**Headers:**
```
Authorization: Bearer {token}
```
**Yanıt:**
```json
[
{
"id": "uuid",
"origin": "https://malicious-site.com",
"reason": "Security threat detected",
"is_active": true,
"created_by": "admin@gauth.local",
"created_at": "2026-02-05T10:00:00Z",
"updated_at": "2026-02-05T10:00:00Z"
}
]
```
### 2. Blacklist Kaydı Oluştur
```http
POST /v1/settings/cors/blacklist
```
**Headers:**
```
Authorization: Bearer {token}
Content-Type: application/json
```
**Body:**
```json
{
"origin": "https://spam-domain.com",
"reason": "Spam attempts detected"
}
```
**Başarılı Yanıt (201):**
```json
{
"id": "new-uuid",
"origin": "https://spam-domain.com",
"reason": "Spam attempts detected",
"is_active": true,
"created_by": "admin@gauth.local",
"created_at": "2026-02-05T11:00:00Z",
"updated_at": "2026-02-05T11:00:00Z"
}
```
### 3. Blacklist Kaydını Güncelle
```http
PUT /v1/settings/cors/blacklist/{id}
```
**Headers:**
```
Authorization: Bearer {token}
Content-Type: application/json
```
**Body (tüm alanlar opsiyonel):**
```json
{
"origin": "https://updated-domain.com",
"reason": "Updated reason",
"is_active": false
}
```
**Başarılı Yanıt (200):**
```json
{
"message": "Blacklist updated successfully"
}
```
### 4. Blacklist Kaydını Sil
```http
DELETE /v1/settings/cors/blacklist/{id}
```
**Headers:**
```
Authorization: Bearer {token}
```
**Başarılı Yanıt (200):**
```json
{
"message": "Blacklist entry deleted successfully"
}
```
---
## 🧪 Kullanım Örnekleri
### Tam İş Akışı (cURL)
```bash
#!/bin/bash
# 1. Admin Login
TOKEN=$(curl -s -X POST http://localhost:8080/v1/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"admin@gauth.local","password":"Admin@123"}' | jq -r '.access_token')
echo "Token: ${TOKEN:0:30}..."
# 2. Whitelist'e domain ekle
echo -e "\n=== Create Whitelist Entry ==="
curl -X POST http://localhost:8080/v1/settings/cors/whitelist \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"origin": "https://myapp.com",
"description": "Production app"
}' | jq .
# 3. Tüm whitelist'i listele
echo -e "\n=== List All Whitelist ==="
curl -X GET http://localhost:8080/v1/settings/cors/whitelist \
-H "Authorization: Bearer $TOKEN" | jq .
# 4. Blacklist'e domain ekle
echo -e "\n=== Create Blacklist Entry ==="
curl -X POST http://localhost:8080/v1/settings/cors/blacklist \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"origin": "https://spam.com",
"reason": "Spam detected"
}' | jq .
# 5. Whitelist entry'yi güncelle (ID'yi yukarıdaki response'dan alın)
WHITELIST_ID="your-whitelist-id-here"
echo -e "\n=== Update Whitelist Entry ==="
curl -X PUT "http://localhost:8080/v1/settings/cors/whitelist/$WHITELIST_ID" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"description": "Updated description",
"is_active": true
}' | jq .
# 6. Blacklist entry'yi sil
BLACKLIST_ID="your-blacklist-id-here"
echo -e "\n=== Delete Blacklist Entry ==="
curl -X DELETE "http://localhost:8080/v1/settings/cors/blacklist/$BLACKLIST_ID" \
-H "Authorization: Bearer $TOKEN" | jq .
```
---
## 🎯 Frontend Entegrasyonu (React)
### API Client
```javascript
class CorsSettingsAPI {
constructor(baseURL, token) {
this.baseURL = baseURL;
this.token = token;
}
// ====== Whitelist ======
async getWhitelist() {
const response = await fetch(`${this.baseURL}/v1/settings/cors/whitelist`, {
headers: {
'Authorization': `Bearer ${this.token}`
}
});
return response.json();
}
async createWhitelist(origin, description) {
const response = await fetch(`${this.baseURL}/v1/settings/cors/whitelist`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ origin, description })
});
return response.json();
}
async updateWhitelist(id, updates) {
const response = await fetch(`${this.baseURL}/v1/settings/cors/whitelist/${id}`, {
method: 'PUT',
headers: {
'Authorization': `Bearer ${this.token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(updates)
});
return response.json();
}
async deleteWhitelist(id) {
const response = await fetch(`${this.baseURL}/v1/settings/cors/whitelist/${id}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${this.token}`
}
});
return response.json();
}
// ====== Blacklist ======
async getBlacklist() {
const response = await fetch(`${this.baseURL}/v1/settings/cors/blacklist`, {
headers: {
'Authorization': `Bearer ${this.token}`
}
});
return response.json();
}
async createBlacklist(origin, reason) {
const response = await fetch(`${this.baseURL}/v1/settings/cors/blacklist`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ origin, reason })
});
return response.json();
}
async updateBlacklist(id, updates) {
const response = await fetch(`${this.baseURL}/v1/settings/cors/blacklist/${id}`, {
method: 'PUT',
headers: {
'Authorization': `Bearer ${this.token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(updates)
});
return response.json();
}
async deleteBlacklist(id) {
const response = await fetch(`${this.baseURL}/v1/settings/cors/blacklist/${id}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${this.token}`
}
});
return response.json();
}
}
// Kullanım
const api = new CorsSettingsAPI('http://localhost:8080', YOUR_ADMIN_TOKEN);
// Whitelist listele
const whitelists = await api.getWhitelist();
console.log(whitelists);
// Yeni whitelist ekle
const newEntry = await api.createWhitelist('https://newapp.com', 'New application');
console.log(newEntry);
```
### React Component Örneği
```jsx
import React, { useState, useEffect } from 'react';
function CorsWhitelistManager() {
const [whitelists, setWhitelists] = useState([]);
const [newOrigin, setNewOrigin] = useState('');
const [newDescription, setNewDescription] = useState('');
const token = localStorage.getItem('admin_token');
useEffect(() => {
fetchWhitelists();
}, []);
const fetchWhitelists = async () => {
try {
const response = await fetch('http://localhost:8080/v1/settings/cors/whitelist', {
headers: {
'Authorization': `Bearer ${token}`
}
});
const data = await response.json();
setWhitelists(data);
} catch (error) {
console.error('Error fetching whitelists:', error);
}
};
const handleCreate = async (e) => {
e.preventDefault();
try {
const response = await fetch('http://localhost:8080/v1/settings/cors/whitelist', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
origin: newOrigin,
description: newDescription
})
});
if (response.ok) {
setNewOrigin('');
setNewDescription('');
fetchWhitelists(); // Refresh list
alert('Whitelist entry created!');
}
} catch (error) {
console.error('Error creating whitelist:', error);
}
};
const handleDelete = async (id) => {
if (!confirm('Are you sure you want to delete this entry?')) return;
try {
const response = await fetch(`http://localhost:8080/v1/settings/cors/whitelist/${id}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`
}
});
if (response.ok) {
fetchWhitelists(); // Refresh list
alert('Whitelist entry deleted!');
}
} catch (error) {
console.error('Error deleting whitelist:', error);
}
};
const toggleActive = async (id, currentStatus) => {
try {
const response = await fetch(`http://localhost:8080/v1/settings/cors/whitelist/${id}`, {
method: 'PUT',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
is_active: !currentStatus
})
});
if (response.ok) {
fetchWhitelists(); // Refresh list
}
} catch (error) {
console.error('Error updating whitelist:', error);
}
};
return (
<div className="cors-whitelist-manager">
<h2>CORS Whitelist Manager</h2>
{/* Add New Entry Form */}
<form onSubmit={handleCreate} className="add-form">
<input
type="text"
placeholder="Origin (e.g., https://example.com)"
value={newOrigin}
onChange={(e) => setNewOrigin(e.target.value)}
required
/>
<input
type="text"
placeholder="Description"
value={newDescription}
onChange={(e) => setNewDescription(e.target.value)}
/>
<button type="submit">Add to Whitelist</button>
</form>
{/* Whitelist Table */}
<table>
<thead>
<tr>
<th>Origin</th>
<th>Description</th>
<th>Active</th>
<th>Created By</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{whitelists.map(entry => (
<tr key={entry.id}>
<td>{entry.origin}</td>
<td>{entry.description}</td>
<td>
<button onClick={() => toggleActive(entry.id, entry.is_active)}>
{entry.is_active ? '✅ Active' : '❌ Inactive'}
</button>
</td>
<td>{entry.created_by}</td>
<td>
<button onClick={() => handleDelete(entry.id)}>Delete</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
export default CorsWhitelistManager;
```
---
## 📊 API Endpoints Özeti
| Endpoint | Method | Açıklama | Admin Required |
|----------|--------|----------|----------------|
| `/v1/settings/cors/whitelist` | GET | Whitelist listele | ✅ |
| `/v1/settings/cors/whitelist` | POST | Whitelist ekle | ✅ |
| `/v1/settings/cors/whitelist/:id` | PUT | Whitelist güncelle | ✅ |
| `/v1/settings/cors/whitelist/:id` | DELETE | Whitelist sil | ✅ |
| `/v1/settings/cors/blacklist` | GET | Blacklist listele | ✅ |
| `/v1/settings/cors/blacklist` | POST | Blacklist ekle | ✅ |
| `/v1/settings/cors/blacklist/:id` | PUT | Blacklist güncelle | ✅ |
| `/v1/settings/cors/blacklist/:id` | DELETE | Blacklist sil | ✅ |
---
## 🔧 Cache Yönetimi
CORS ayarları Redis'te cache'lenir:
- **Cache süresi:** 1 saat
- **Otomatik invalidation:** Create/Update/Delete işlemlerinde
- **Cache key:**
- Whitelist: `cors:whitelist`
- Blacklist: `cors:blacklist`
---
## ✅ Test Checklist
- [ ] Admin token alındı
- [ ] Whitelist ekleme testi
- [ ] Whitelist listeleme testi
- [ ] Whitelist güncelleme testi
- [ ] Whitelist silme testi
- [ ] Blacklist ekleme testi
- [ ] Blacklist listeleme testi
- [ ] Blacklist güncelleme testi
- [ ] Blacklist silme testi
- [ ] Swagger dokümantasyonu kontrol edildi
**CORS Whitelist & Blacklist API'leri tam çalışır durumda!** 🚀