7.2 KiB
7.2 KiB
Authentication Kurulum Kılavuzu
Bu Next.js projesi Django REST API ile entegre çalışan tam özellikli bir authentication sistemi içerir.
📋 Özellikler
✅ Email/Password ile kayıt ve giriş ✅ Email aktivasyonu ✅ Social Auth (Google, GitHub) ✅ Token refresh (JWT) ✅ Şifre sıfırlama ✅ Kullanıcı profili ✅ Session yönetimi
🚀 Kurulum
1. Environment Variables
.env.local dosyası oluşturun (.env.example dosyasını kopyalayın):
cp .env.example .env.local
.env.local dosyasını düzenleyin:
# NextAuth Configuration
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=super-secret-key-change-this
# Django REST API
NEXT_PUBLIC_API_BASE_URL=http://localhost:8000/api/v1
# Social Auth (İsteğe bağlı)
GOOGLE_ID=your-google-client-id
GOOGLE_SECRET=your-google-client-secret
GITHUB_ID=your-github-client-id
GITHUB_SECRET=your-github-client-secret
2. NextAuth Secret Üretme
openssl rand -base64 32
Bu komutu çalıştırın ve çıkan değeri NEXTAUTH_SECRET olarak kullanın.
3. Django Backend
Django backend'inizin çalıştığından emin olun:
# Django projenizde
python manage.py runserver
Backend http://localhost:8000 adresinde çalışıyor olmalı.
📱 Sayfalar ve Rotalar
Authentication Sayfaları
| Sayfa | Route | Açıklama |
|---|---|---|
| Login | /auth/login |
Giriş sayfası (Email/Password + Social) |
| Register | /auth/register |
Kayıt sayfası |
| Activate | /auth/activate/[uid]/[token] |
Email aktivasyon sayfası |
| Resend Activation | /auth/resend-activation |
Aktivasyon emaili tekrar gönderme |
| Password Reset | /auth/password-reset |
Şifre sıfırlama talebi |
| Reset Confirm | /auth/password-reset/confirm/[uid]/[token] |
Şifre sıfırlama onayı |
| Error | /auth/error |
Auth hata sayfası |
Korumalı Sayfalar
| Sayfa | Route | Açıklama |
|---|---|---|
| Profile | /profile |
Kullanıcı profili |
| Dashboard | /dashboard |
Dashboard (mevcut) |
🔐 Social Authentication Kurulumu
Google OAuth2
- Google Cloud Console adresine gidin
- Yeni proje oluşturun veya mevcut projeyi seçin
- "APIs & Services" > "Credentials" sayfasına gidin
- "Create Credentials" > "OAuth 2.0 Client ID" seçin
- Application type: "Web application"
- Authorized redirect URIs:
http://localhost:3000/api/auth/callback/googlehttps://yourdomain.com/api/auth/callback/google(production)
- Client ID ve Client Secret'i kopyalayıp
.env.localdosyasına ekleyin
GitHub OAuth2
- GitHub Developer Settings adresine gidin
- "New OAuth App" butonuna tıklayın
- Form bilgileri:
- Application name: "Your App Name"
- Homepage URL:
http://localhost:3000 - Authorization callback URL:
http://localhost:3000/api/auth/callback/github
- Client ID ve Client Secret'i
.env.localdosyasına ekleyin
🔄 Authentication Flow
1. Kayıt (Register)
User fills form → POST /auth/users/ → Email sent → User clicks link →
Account activated → User can login
2. Login (Email/Password)
User enters credentials → POST /auth/jwt/create/ → Tokens received →
Session created → User authenticated
3. Social Login
User clicks Google/GitHub → OAuth flow → Access token received →
POST /auth/social/{provider}/ → Tokens received → Session created
4. Token Refresh
Access token expires → Auto refresh with refresh token →
New tokens received → Session updated
🛡️ Middleware ve Koruma
Session Kontrolü
import { useSession } from "next-auth/react";
export default function ProtectedPage() {
const { data: session, status } = useSession();
if (status === "loading") {
return <div>Loading...</div>;
}
if (status === "unauthenticated") {
redirect("/auth/login");
}
return <div>Protected content</div>;
}
API İsteği Örnekleri
// Get user profile
const response = await fetch(`${API_BASE_URL}/auth/users/me/`, {
headers: {
Authorization: `Bearer ${session.accessToken}`,
},
});
// Update user profile
const response = await fetch(`${API_BASE_URL}/auth/users/me/`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${session.accessToken}`,
},
body: JSON.stringify({
first_name: "Yeni Ad",
last_name: "Yeni Soyad",
}),
});
📧 Email Testleri (Development)
Django backend'inizde MailPit veya benzeri bir email test aracı kullanıyorsanız:
MailPit: http://localhost:8025
Gönderilen aktivasyon ve şifre sıfırlama emaillerini burada görebilirsiniz.
🧪 Test Senaryoları
1. Email/Password Kayıt
1. /auth/register sayfasına gidin
2. Form bilgilerini doldurun
3. "Kayıt Ol" butonuna tıklayın
4. Email kutunuzu kontrol edin (MailPit: http://localhost:8025)
5. Aktivasyon linkine tıklayın
6. Hesap aktifleştirilir
7. /auth/login sayfasından giriş yapın
2. Social Login
1. /auth/login sayfasına gidin
2. "Google ile Giriş Yap" veya "GitHub ile Giriş Yap" butonuna tıklayın
3. OAuth akışını tamamlayın
4. Otomatik olarak dashboard'a yönlendirilirsiniz
3. Şifre Sıfırlama
1. /auth/password-reset sayfasına gidin
2. Email adresinizi girin
3. Email kutunuzu kontrol edin
4. Şifre sıfırlama linkine tıklayın
5. Yeni şifrenizi girin
6. Yeni şifre ile giriş yapın
🐛 Hata Ayıklama
"Authentication failed" hatası
- Django backend'in çalıştığından emin olun
- API_BASE_URL değerini kontrol edin
- Browser console'da hata mesajlarını kontrol edin
Social auth çalışmıyor
- Google/GitHub OAuth credentials'ları doğru mu?
- Redirect URI'lar doğru ayarlanmış mı?
- Django backend'de social auth ayarları yapılmış mı?
Token expired hatası
- Token refresh otomatik çalışmalı
- Refresh token süresi dolmuşsa yeniden login gerekli
- Session süresi: 7 gün (refresh token)
📝 TypeScript Types
// next-auth.d.ts (mevcut)
interface User {
accessToken?: string;
refreshToken?: string;
expires?: number;
accessTokenExpiry?: number;
}
interface Session {
accessToken?: string;
refreshToken?: string;
expires?: number;
error?: string;
}
🔗 Faydalı Linkler
💡 İpuçları
- Development:
.env.localdosyasını git'e eklemeyin - Production: Environment variables'ı hosting platformunuzda ayarlayın
- Security: NEXTAUTH_SECRET'i güçlü ve rastgele tutun
- CORS: Django backend'de Next.js URL'ini CORS whitelist'e ekleyin
- HTTPS: Production'da mutlaka HTTPS kullanın
🚀 Production Deployment
- Environment variables'ı production ortamına ekleyin
NEXTAUTH_URL'i production URL'inize değiştirin- Django backend URL'ini production URL'i ile değiştirin
- OAuth redirect URI'larını production URL'leri ile güncelleyin
- HTTPS kullanın (NextAuth requirement)
Last Updated: 2025-12-24