Yes,you could.
For this what you could do is assign each User a particular role.For example ,in your case,assign user who owns the items as role column ADMIN and all others ANONYMOUS or USER,you pick.After this, using spring security you could make the request fail for the users having ANONYMOUS or USER role for the items URL and only allow users with ADMIN role to view the items.
Now,this could be achieved via spring security in multiple ways :
1.Using @PreAuthorize tags for individual controller methods and testing roles ADMIN/USER/..
But,i guess ,you do not want to modify the controller as such drastically.
The short manual way,which is,to create authentication object into context holder and use spring boot security config,such as below,for example :
@Order(1)
public class UserFilter extends Filter {
@Autowired
UserService userService;
...
UserObject userObject = userService.getUser(arg..);
List<GrantedAuthority> grantedAuthorityList = new ArrayList<GrantedAuthority>();
grantedAuthorityList.add( new SimpleGrantedAuthority((userObject.getRoleName()));//Either ROLE_ADMIN or ROLE_USER
Authentication authentication = new PreAuthenticatedAuthenticationToken(userObject.getId(), new Object(), grantedAuthorityList);
SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(request,response);
...
}
And the security configuration class :
@Configuration
@EnableWebSecurity
public class SecurityConfigREST extends WebSecurityConfigurerAdapter {
SecurityConfigREST(){
super(true);
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
PreAuthenticatedAuthenticationProvider pap=new PreAuthenticatedAuthenticationProvider();
pap.setPreAuthenticatedUserDetailsService(new PreAuthenticatedGrantedAuthoritiesUserDetailsService());
auth.authenticationProvider(pap);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.regexMatchers("^/items.*$").hasAuthority("ROLE_ADMIN") //The role which should have access to /items/1,2.. URL
.anyRequest().authenticated();
}
}
- Use UserDetailsService in the security config above and load the user and its role in a preauthenticated authentication provider.
Refer : http://docs.spring.io/autorepo/docs/spring-security/3.2.2.RELEASE/apidocs/org/springframework/security/core/userdetails/UserDetailsService.html
Having said all that ,its also a good design not to pass items (1,2,3) numbers via URL,as could lead to potential issues later,so use GET and pass JSON request body to it such as :
/items RequestMethod.GET
{
"itemList" : [1,2,3,4,5]
}
Hope that helps.