Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

How do you implement method-level security with @PreAuthorize and @PostAuthorize? @PreAuthorize और @PostAuthorize से मेथड-लेवल सिक्योरिटी कैसे इम्प्लीमेंट करें?

Answer

Method-level security lets you enforce authorization rules directly on service or controller methods instead of only at the URL level, enabled with @EnableMethodSecurity. @PreAuthorize evaluates a SpEL expression before the method executes and blocks the call if it evaluates to false, commonly checking roles or matching the authenticated user against a method argument.

@PostAuthorize evaluates after the method executes, allowing checks against the returned object (e.g. ensuring a fetched document belongs to the requesting user), and @PreFilter/@PostFilter can filter collection arguments or return values based on a condition per element.

@PreAuthorize("hasRole('ADMIN') or #userId == authentication.principal.id")
public User getUser(Long userId) { ... }

@PostAuthorize("returnObject.owner == authentication.name")
public Document getDocument(Long id) { ... }

मेथड-लेवल सिक्योरिटी आपको केवल URL-लेवल के बजाय सीधे सर्विस या कंट्रोलर मेथड्स पर ऑथराइज़ेशन नियम लागू करने देती है, जिसे @EnableMethodSecurity से सक्षम किया जाता है। @PreAuthorize मेथड चलने से पहले एक SpEL एक्सप्रेशन का मूल्यांकन करता है और यदि यह false हो तो कॉल को ब्लॉक कर देता है।

@PostAuthorize मेथड चलने के बाद मूल्यांकन करता है, जिससे रिटर्न किए गए ऑब्जेक्ट के विरुद्ध जाँच की जा सकती है, और @PreFilter/@PostFilter प्रति एलिमेंट कंडीशन के आधार पर कलेक्शन को फ़िल्टर कर सकते हैं।

@PreAuthorize("hasRole('ADMIN') or #userId == authentication.principal.id")
public User getUser(Long userId) { ... }

@PostAuthorize("returnObject.owner == authentication.name")
public Document getDocument(Long id) { ... }

Was this answer clear?