0

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.

Vijay Muvva
  • 1,063
  • 1
  • 17
  • 31
  • How have you configured your URL security? Is that URI secured? – aksappy Jul 18 '16 at 12:53
  • I suppose for all the URLs authorization happens through auth server, I am giving a bearer token - curl -H "Authorization: Bearer 116bf2f0-d0a8-4c81-ab8d-56b64f269cc0" localhost:40073/accessibleByAdminOnly and I see the following {"error":"access_denied","error_description":"Access is denied"} – Vijay Muvva Jul 18 '16 at 13:20
  • Okay so you need to configure your http urls and provide an intercept pattern and secure them so that Spring Security knows about it. – aksappy Jul 18 '16 at 13:31
  • Show me all the configuration that you have on your application, as much as possible atleast – aksappy Jul 18 '16 at 13:31
  • 1
    Implemented the solution suggested by stalet on http://stackoverflow.com/questions/35088918/spring-oauth2-hasrole-access-denied – Vijay Muvva Jul 21 '16 at 11:44
  • You can answer your own question - might be of help to someone else – aksappy Jul 21 '16 at 11:55

0 Answers0