Skip to content

Commit b35d3f5

Browse files
committed
feat: Add authentication example application with User entity, repository, and security config
1 parent 9644c82 commit b35d3f5

File tree

6 files changed

+449
-0
lines changed

6 files changed

+449
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package examples.auth_example;
2+
3+
import jazzyframework.di.annotations.Component;
4+
import jazzyframework.security.config.SecurityConfig;
5+
6+
/**
7+
* Security configuration for the Authentication Example Application.
8+
*
9+
* <p>This configuration demonstrates how to set up URL-based security rules
10+
* for a typical web application with authentication endpoints.
11+
*
12+
* <h3>Security Rules:</h3>
13+
* <ul>
14+
* <li><b>Public endpoints:</b> Home page and authentication endpoints</li>
15+
* <li><b>Secure endpoints:</b> Protected resources requiring JWT token</li>
16+
* <li><b>Admin endpoints:</b> Administrative functions requiring ADMIN role</li>
17+
* </ul>
18+
*
19+
* <p>The {@code @Component} annotation ensures this configuration is automatically
20+
* discovered and used by the Jazzy Framework's security system.
21+
*
22+
* @author Caner Mastan
23+
* @see SecurityConfig
24+
*/
25+
@Component
26+
public class AppSecurityConfig extends SecurityConfig {
27+
28+
/**
29+
* Configures security rules for the application.
30+
*
31+
* <p>This method defines which endpoints are public, which require authentication,
32+
* and which require admin privileges. The configuration uses wildcards to
33+
* efficiently cover multiple related endpoints.
34+
*/
35+
@Override
36+
public void configure() {
37+
// Define public endpoints (no authentication required)
38+
publicEndpoints(
39+
"/", // Home page - welcome message
40+
"/api/auth/**" // All auth endpoints (register, login, me)
41+
);
42+
43+
// Define secure endpoints (authentication required)
44+
requireAuth(
45+
"/api/protected", // Example protected endpoint
46+
"/api/user/**" // User-specific endpoints (profile, settings, etc.)
47+
);
48+
49+
// Define admin endpoints (admin role required)
50+
requireRole("ADMIN",
51+
"/api/admin/**" // Administrative endpoints (user management, etc.)
52+
);
53+
}
54+
}
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package examples.auth_example;
2+
3+
import jazzyframework.core.Config;
4+
import jazzyframework.core.Server;
5+
import jazzyframework.routing.Router;
6+
import jazzyframework.security.annotations.EnableJazzyAuth;
7+
import jazzyframework.security.annotations.LoginMethod;
8+
9+
/**
10+
* Authentication Example Application
11+
*
12+
* This example demonstrates how to use @EnableJazzyAuth annotation
13+
* to automatically enable authentication endpoints in your Jazzy application.
14+
*
15+
* Features enabled:
16+
* - POST /api/auth/register - User registration
17+
* - POST /api/auth/login - User login
18+
* - GET /api/auth/me - Get current user info
19+
*
20+
* JWT authentication with email-based login
21+
*/
22+
@EnableJazzyAuth(
23+
userClass = User.class,
24+
repositoryClass = UserRepository.class,
25+
loginMethod = LoginMethod.EMAIL,
26+
jwtExpirationHours = 24,
27+
authBasePath = "/api/auth"
28+
)
29+
public class AuthExampleApp {
30+
31+
public static void main(String[] args) {
32+
System.out.println("🚀 Starting Jazzy Auth Example Application...");
33+
34+
Config config = new Config();
35+
config.setEnableMetrics(true);
36+
config.setServerPort(8080);
37+
38+
Router router = new Router();
39+
40+
// Configure routes
41+
configureRoutes(router);
42+
43+
// Start server
44+
Server server = new Server(router, config);
45+
server.start(config.getServerPort());
46+
47+
System.out.println("✅ Authentication endpoints available:");
48+
System.out.println("📝 POST /api/auth/register - Register new user");
49+
System.out.println("🔐 POST /api/auth/login - User login");
50+
System.out.println("👤 GET /api/auth/me - Get current user");
51+
System.out.println("🌐 Server running on http://localhost:" + config.getServerPort());
52+
}
53+
54+
/**
55+
* Configure application routes
56+
*/
57+
private static void configureRoutes(Router router) {
58+
// Example: Public welcome endpoint
59+
router.GET("/", "home", HomeController.class);
60+
61+
// Example: Protected endpoint (requires authentication in SecurityConfig)
62+
router.GET("/api/protected", "protectedEndpoint", HomeController.class);
63+
}
64+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package examples.auth_example;
2+
3+
import jazzyframework.http.Request;
4+
import jazzyframework.http.Response;
5+
import jazzyframework.http.JSON;
6+
7+
/**
8+
* Home Controller for Auth Example
9+
*/
10+
public class HomeController {
11+
12+
/**
13+
* Welcome endpoint
14+
* GET /
15+
*/
16+
public Response home(Request request) {
17+
return Response.json(
18+
JSON.of(
19+
"message", "Welcome to Jazzy Auth Example!",
20+
"endpoints", new String[]{
21+
"POST /api/auth/register",
22+
"POST /api/auth/login",
23+
"GET /api/auth/me",
24+
"GET /api/protected (requires Bearer token)"
25+
}
26+
)
27+
);
28+
}
29+
30+
/**
31+
* Protected endpoint example - JWT validation handled automatically by SecurityInterceptor
32+
* GET /api/protected
33+
*/
34+
public Response protectedEndpoint(Request request) {
35+
return Response.json(
36+
JSON.of(
37+
"message", "This is a protected endpoint!",
38+
"note", "You successfully accessed a protected endpoint with JWT!",
39+
"info", "JWT validation was handled automatically by SecurityInterceptor"
40+
)
41+
);
42+
}
43+
}
Lines changed: 191 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,191 @@
1+
# Jazzy Framework - Authentication Example
2+
3+
Bu örnek uygulama, `@EnableJazzyAuth` annotation'ının nasıl kullanılacağını gösterir.
4+
5+
## Özellikler
6+
7+
- 📧 **Email tabanlı authentication**
8+
- 🔐 **JWT token sistemi**
9+
- 🚀 **Zero-configuration setup**
10+
- 📝 **Otomatik endpoint'ler**
11+
12+
## Otomatik Oluşturulan Endpoint'ler
13+
14+
`@EnableJazzyAuth` annotation'ı otomatik olarak şu endpoint'leri oluşturur:
15+
16+
### 1. Kullanıcı Kaydı
17+
```
18+
POST /api/auth/register
19+
Content-Type: application/json
20+
21+
{
22+
"email": "[email protected]",
23+
"password": "password123",
24+
"name": "John Doe"
25+
}
26+
```
27+
28+
**Başarılı Yanıt:**
29+
```json
30+
{
31+
"message": "User registered successfully",
32+
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
33+
"user": {
34+
"id": "1",
35+
"email": "[email protected]"
36+
}
37+
}
38+
```
39+
40+
### 2. Kullanıcı Girişi
41+
```
42+
POST /api/auth/login
43+
Content-Type: application/json
44+
45+
{
46+
"email": "[email protected]",
47+
"password": "password123"
48+
}
49+
```
50+
51+
**Başarılı Yanıt:**
52+
```json
53+
{
54+
"message": "Login successful",
55+
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
56+
"user": {
57+
"id": "1",
58+
"email": "[email protected]"
59+
}
60+
}
61+
```
62+
63+
### 3. Mevcut Kullanıcı Bilgisi
64+
```
65+
GET /api/auth/me
66+
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
67+
```
68+
69+
**Başarılı Yanıt:**
70+
```json
71+
{
72+
"user": {
73+
"id": "1",
74+
"email": "[email protected]",
75+
"username": null
76+
}
77+
}
78+
```
79+
80+
## Nasıl Çalıştırılır
81+
82+
1. **Uygulamayı başlatın:**
83+
```bash
84+
javac -cp "lib/*" src/main/java/examples/auth_example/*.java
85+
java -cp "lib/*:src/main/java" examples.auth_example.AuthExampleApp
86+
```
87+
88+
2. **Test edin:**
89+
```bash
90+
# Kullanıcı kaydı
91+
curl -X POST http://localhost:8080/api/auth/register \
92+
-H "Content-Type: application/json" \
93+
-d '{"email":"[email protected]","password":"123456","name":"Test User"}'
94+
95+
# Giriş yapın
96+
curl -X POST http://localhost:8080/api/auth/login \
97+
-H "Content-Type: application/json" \
98+
-d '{"email":"[email protected]","password":"123456"}'
99+
100+
# Token ile kullanıcı bilgisi alın
101+
curl -X GET http://localhost:8080/api/auth/me \
102+
-H "Authorization: Bearer YOUR_TOKEN_HERE"
103+
```
104+
105+
## Configuration
106+
107+
`@EnableJazzyAuth` annotation'ı şu parametreleri destekler:
108+
109+
```java
110+
@EnableJazzyAuth(
111+
userClass = User.class, // Kullanıcı entity class'ı
112+
repositoryClass = UserRepository.class, // Kullanıcı repository interface'i
113+
loginMethod = LoginMethod.EMAIL, // EMAIL, USERNAME, veya BOTH
114+
jwtExpirationHours = 24, // JWT token süresi (saat)
115+
authBasePath = "/api/auth" // Auth endpoint'lerinin base path'i
116+
)
117+
```
118+
119+
## Gereksinimler
120+
121+
### User Entity
122+
123+
User class'ınız şu field'lara sahip olmalı:
124+
125+
- `id` (Long) - Kullanıcı ID'si
126+
- `email` (String) - Email adresi (EMAIL veya BOTH login method için)
127+
- `username` (String) - Kullanıcı adı (USERNAME veya BOTH login method için)
128+
- `password` (String) - Şifre (otomatik hash'lenir)
129+
130+
### User Repository
131+
132+
User repository interface'iniz `BaseRepository`'yi extend etmelidir:
133+
134+
```java
135+
public interface UserRepository extends BaseRepository<User, Long> {
136+
// İsteğe bağlı özel query methodları ekleyebilirsiniz
137+
// Optional<User> findByEmail(String email);
138+
// Optional<User> findByUsername(String username);
139+
}
140+
```
141+
142+
**Not:** Repository interface'i otomatik olarak Jazzy Framework'ün DI container'ında register edilir.
143+
144+
## Güvenlik Konfigürasyonu (Opsiyonel)
145+
146+
Endpoint'leri korumak için `SecurityConfig` class'ı oluşturabilirsiniz:
147+
148+
```java
149+
@Component
150+
public class AppSecurityConfig extends SecurityConfig {
151+
152+
@Override
153+
public void configure() {
154+
// Public endpoint'ler (authentication gerektirmez)
155+
publicEndpoints(
156+
"/", // Ana sayfa
157+
"/api/auth/**" // Tüm auth endpoint'leri
158+
);
159+
160+
// Secure endpoint'ler (authentication gerektirir)
161+
requireAuth(
162+
"/api/protected", // Korumalı endpoint
163+
"/api/user/**" // Kullanıcıya özel endpoint'ler
164+
);
165+
166+
// Admin endpoint'leri (ADMIN rolü gerektirir)
167+
requireRole("ADMIN",
168+
"/api/admin/**" // Admin endpoint'leri
169+
);
170+
}
171+
}
172+
```
173+
174+
### Wildcard Destek
175+
176+
SecurityConfig şu wildcard'ları destekler:
177+
178+
- `*` - Tek path segment'i ile eşleşir
179+
- `**` - Herhangi sayıda path segment'i ile eşleşir
180+
181+
**Örnekler:**
182+
- `/api/auth/**``/api/auth/login`, `/api/auth/register`, `/api/auth/user/profile` ile eşleşir
183+
- `/user/*``/user/123` ile eşleşir ama `/user/123/profile` ile eşleşmez
184+
185+
## Avantajları
186+
187+
-**Zero Configuration** - Sadece annotation ekleyin
188+
-**Otomatik JWT** - Token üretimi ve doğrulama otomatik
189+
-**Flexible User Entity** - Kendi User class'ınızı kullanın
190+
-**Multiple Login Methods** - Email, username veya her ikisi
191+
-**Standard Java** - External dependency yok

0 commit comments

Comments
 (0)