How can i have method level security in resource server using spring security oauth2? I am aware of client scopes and roles, I am talking about method level security using user roles something like -
@PreAuthorize("hasRole('ROLE_ADMIN')")
@RequestMapping("/accessibleByAdminOnly")
public String accessibleByAdminOnly() {
return "Welcome Admin!";
}
My resource server config looks like this -
@SpringBootApplication
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class DemoAPIServiceApp extends GlobalMethodSecurityConfiguration {
@Autowired
private ApplicationContext applicationContext;
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
DefaultMethodSecurityExpressionHandler methodSecurityExpressionHandler = new DefaultMethodSecurityExpressionHandler();
methodSecurityExpressionHandler.setRoleHierarchy(roleHierarchy());
methodSecurityExpressionHandler.setApplicationContext(applicationContext);
return methodSecurityExpressionHandler;
}
@Bean
public RoleHierarchy roleHierarchy() {
RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
roleHierarchy.setHierarchy("ROLE_ADMIN > ROLE_USER");
return roleHierarchy;
}
@Bean
public RoleVoter roleVoter() {
return new RoleHierarchyVoter(roleHierarchy());
}
public static void main(String[] args) {
SpringApplication.run(DemoAPIServiceApp.class, args);
}
}
I am using a standard spring oauth2 auth server configuration with custom user details. I have one client and one scope.
Please help. The method level security is not working with this configuration.