Using Spring Security pre and post annotations

Spring Security pre and post annotations allow even more complex authorization checks to be carried before securing methods.

You can enable pre and post annotations by using the prePostEnabled = true annotation on @EnableGlobalMethodSecurity:

@EnableGlobalMethodSecurity(prePostEnabled = true)
@SpringBootApplication
public class SpringSecurityApplication {

The following code adds PreAuthorize to the method in order to check for user roles. You can specify a Spring Expression Language (SpEL), expression to check for authorization before executing the method:

@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_USER')")
public User retrieveUser(String userName) {
// Your code
}

You can access principal and authentication objects from security contexts in EL expressions.

The following example checks whether the value of the parameter name is the same as the principal's username:

@PreAuthorize("#name == authentication.principal.username")

PostAuthorize allows you to execute checks after method execution. You can also use the return value from a method using returnObject:

@PostAuthorize("returnObject.name == authentication.principal.username")
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset