Reputation: 45
I have a spring data repository and I used @RepositoryRestResource
annotation to generate REST resources for it. Now I want to control access on it using spring security.
I know it is possible to put @PreAutorize
on methods or use WebSecurityConfigurerAdapter
to perform authorization according to request paths. But none of these solutions work for me. Because the former secures the methods while I need to only apply it when a HTTP request is trying to call method and the latter seems bad to me because I need to modify a single class after adding each new repository. (kinda violation of Open-Closed Principle, IMHO) if I I prefer to put access control rules of each resource beside that resource not to put somewhere else and tie them using paths or names.
So I have two criteria for the access control solution:
@RepositoryRestResource
@PreAuthorize("hasRole('ADMIN')")
public interface VehicleRepository extends CrudRepository<Vehicle,Integer>{
}
This is the first solution which does not work for me.
@Configuration
@EnableGlobalMethodSecurity(
prePostEnabled = true,
securedEnabled = true,
jsr250Enabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
...
@Override
protected void configure(HttpSecurity http) throws Exception {
...
http.authorizeRequests().antMatchers("/vehicles/**").hasRole("ADMIN");
...
}
...
}
and this a second solution which I don't like as I described.
I'd like to know if there is any other solutions. I've read reference documentations and searched the web but I didn't find what I want.
Note that I want to use RepositoryRestResource
so please don't say "write your own controller".
Sorry for long question and thank you in advance.
Upvotes: 0
Views: 1183
Reputation: 1298
You can annotate the methods from CrudRepository, like this:
@PreAuthorize("hasRole('ADMIN')")
@Override
Optional<Vehicle> findById(Integer id);
You can find more information in the Spring Data REST Docs: https://docs.spring.io/spring-data/rest/reference/security.html
Upvotes: 2