Return to site
🍃🎓 SPRING CERTIFICATION QUESTION: What do @PreAuthorized and @RolesAllowed do? What is the difference between them?
🍃🎓 SPRING CERTIFICATION QUESTION: What do @PreAuthorized and @RolesAllowed do? What is the difference between them?
·
🙆♂️Similarities:
Both of these annotations might be used to apply authorization logic at a method level.
Access control for both annotations is applied before method invocation.
🙅♀️Discrepancies:
RolesAllowed supports only a list of authentications (roles). It's an annotation defined by JSR-250 specification.
PreAuthorize supports SpEL, it's a Spring Security framework annotation.
import org.springframework.security.access.prepost.PreAuthorize; import javax.annotation.security.RolesAllowed; public class SpringSecuSample { //Using @PreAuthorize Annotation @PreAuthorize("hasRole('ROLE_VIEWER') or hasRole('ROLE_EDITOR')") public boolean isValidUsername3(String username) { //... return false; } @PreAuthorize("#username == authentication.principal.username") public String getMyRoles(String username) { //... return null; } //Using @RolesAllowed Annotation @RolesAllowed("ROLE_VIEWER") public String getUsername2() { //... return null; } @RolesAllowed({ "ROLE_VIEWER", "ROLE_EDITOR" }) public boolean isValidUsername2(String username) { //... return false; } }
#spring #certificationquestion #vcp
Introduction to Spring Security👉 https://www.baeldung.com/spring-security-method-security