Authorization
Authorization decide karta hai AUTHENTICATED user KYA kar sakta hai. Do levels par apply hoti hai — URL-LEVEL (SecurityFilterChain mein requestMatchers().hasRole()) aur METHOD-LEVEL (@PreAuthorize annotation, individual method par). Method-level security ZYAADA GRANULAR control deती hai.
ROLES (jaise ADMIN, USER) broad categories hain — Spring internally "ROLE_" prefix add karta hai. AUTHORITIES zyaada FINE-GRAINED permissions ke liye hote hain (jaise "DELETE_USER", "APPROVE_PAYMENT") — bade systems mein, roles ek SET of authorities REPRESENT karte hain.
@RestController
public class AdminController {
@PreAuthorize("hasRole('ADMIN')")
@DeleteMapping("/api/users/{id}")
public void deleteUser(@PathVariable Long id) {
// Sirf ADMIN role wale users ye endpoint hit kar sakte hain
}
@PreAuthorize("#userId == authentication.principal.id or hasRole('ADMIN')")
@GetMapping("/api/users/{userId}/profile")
public User getProfile(@PathVariable Long userId) {
// User APNI profile dekh sake, YA admin kisi ki bhi
}
}
// Method-level security enable karna:
@Configuration
@EnableMethodSecurity
public class SecurityConfig { }- URL-level (SecurityFilterChain) aur method-level (@PreAuthorize) authorization
- Role = broad category, Authority = fine-grained permission
- @PreAuthorize SpEL expressions support karta hai — complex conditions bhi possible
URL-level security ke ALAWA, METHOD-level security bhi ho sakti hai — @PreAuthorize("hasRole('ADMIN')") ek SPECIFIC method par lagाके, granular control milता hai (jaise EK method sirf ADMIN role access kar sake, chahe URL security allow kar rahi ho).
@Service
public class AdminService {
@PreAuthorize("hasRole('ADMIN')")
public void deleteAllUsers() {
// Sirf ADMIN role wale users ye method call kar sakte hain
}
@PreAuthorize("#userId == authentication.principal.id")
public User getOwnProfile(Long userId) {
// User sirf APNI profile access kar sake — SpEL expression
}
}ROLE ek SPECIAL TYPE ki AUTHORITY hai — Spring Security internally "ROLE_" prefix ADD karta hai (jaise "ADMIN" role → "ROLE_ADMIN" authority). hasRole('ADMIN') aur hasAuthority('ROLE_ADMIN') FUNCTIONALLY SAME hain. AUTHORITIES zyaada GRANULAR permissions ke liye use hoti hain (jaise "READ_REPORTS", "WRITE_REPORTS").
- Role = broad category (ADMIN, USER) — internally "ROLE_" prefix
- Authority = granular permission (READ_REPORTS, DELETE_USER)
- hasRole('X') === hasAuthority('ROLE_X')