I am creating a Restful API with Spring Boot 2.5 and would like to know the right way to implement validation while checking roles for some routes. Also, for some routes I need to make sure that only admins can modify the resource or its owner.
@PreAuthorize
seems to be the solution, but @Valid
seems to be processed before an actual method call, otherwise known as executed before @PreAuthorize
.
See : How to check security acess (@Secured or @PreAuthorize) before validation (@Valid) in my Controller?
Is this really the only available and clean solution to make a Restful API with both validation and roles with Spring Boot & Spring Security?
CodePudding user response:
I'm afraid that that is the cleanest solution.
To check roles for some routes, you can configure your HttpSecurity
to check roles before even getting to the controller, like so:
@Bean
SecurityFilterChain app(HttpSecurity http) throws Exception {
http.authorizeHttpRequests((requests) -> requests
.antMatchers("/route1").hasAnyRole("ADMIN", "USER")
)
return http.build();
}
So, with this configuration, you are making sure that only ROLE_USER
or ROLE_ADMIN
are allowed to request /route1
.
But now, the ROLE_USER
is allowed only if they are the resource owners. For this, you must have to resolve the method parameters to know which resource you are requesting. And then, in the @PreAuthorize
, you can do something like this:
@PreAuthorize("@myBean.isResourceOwner(resourceId, authentication)")
@PutMapping("/{resourceId}")
public void update(@PathVariable Long resourceId) {
...
}