countryroadscat
countryroadscat

Reputation: 1750

Role hierarchy and OAuth2 Security using Spring Boot

I know there is a lot of threads about Role hierarchy however I could not find any example combined with OAuth2.

So, most of threads point that I need to implement RoleHierarchy bean:

Beans.java

@EnableJpaRepositories(basePackages = "com.template.service.repository")
@EnableAspectJAutoProxy
@ComponentScan
@Configuration
public class Beans {
@Bean
public ItemService itemsService(ItemsRepository itemsRepository) {
    return new ItemService(itemsRepository);
}

@Bean
public RoleHierarchy roleHierarchy(){
    RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
    roleHierarchy.setHierarchy("ROLE_SUPREME > ROLE_DEVELOPER ROLE_DEVELOPER > ROLE_ADMIN  ROLE_ADMIN > ROLE_USER");
    return roleHierarchy;
}

@Bean
public DtoMapper dtoMapper() {
    return new DtoMapper();
}
}

Next, I need to @Autowire this bean to my WebSecurityConfigurerAdapter. However becouse I'm using OAuth2 security so I have HttpSecurity configured inside ResourceServerConfigurerAdapter.

OAuth2.java

public class OAuth2 {
@EnableAuthorizationServer
@Configuration
@ComponentScan
public static class AuthorizationServer extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManagerBean;
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("trusted_client")
                .authorizedGrantTypes("password", "refresh_token")
                .scopes("read", "write");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManagerBean).userDetailsService(userDetailsService);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.allowFormAuthenticationForClients();
    }
}

@EnableResourceServer
@Configuration
@ComponentScan
public static class ResourceServer extends ResourceServerConfigurerAdapter {

    @Autowired
    private RoleHierarchy roleHierarchy;

    private SecurityExpressionHandler<FilterInvocation> webExpressionHandler() {
        OAuth2WebSecurityExpressionHandler defaultWebSecurityExpressionHandler = new OAuth2WebSecurityExpressionHandler();
        defaultWebSecurityExpressionHandler.setRoleHierarchy(roleHierarchy);
        return defaultWebSecurityExpressionHandler;
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests().expressionHandler(webExpressionHandler())
                .antMatchers("/api/**").hasRole("DEVELOPER");
    }
}
}

Security.java

@EnableWebSecurity
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
@Configuration
@ComponentScan
public class Security extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService userDetailsService;

@Bean
public JpaAccountDetailsService userDetailsService(AccountsRepository accountsRepository) {
    return new JpaAccountDetailsService(accountsRepository);
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

@Bean
public PasswordEncoder passwordEncoder(){
    return new BCryptPasswordEncoder();
} 
}

However hierarchy is not working. Request with credentials for SUPREME user ends with:

{
  "error": "access_denied",
  "error_description": "Access is denied"
}

When I switch hasRole("DEVELOPER") to hasRole("SUPREME") - everything works fine.

I'm using Spring Boot 1.5.2 and Spring Security OAuth 2.1.0.RELEASE

UPDATE

When i comment all OAuth2.java class and move webExpressionHandler() method signature to Security.java class - role hierarchy works fine. So what is going on with OAuth2 Resource Server?

Upvotes: 2

Views: 1092

Answers (2)

K&#252;bra
K&#252;bra

Reputation: 197

That's how it worked successfully.I have tested.

ROLE_SUPREME > ROLE_DEVELOPER > ROLE_ADMIN

Code blog as follows

@Bean
public static RoleHierarchyImpl roleHierarchy() {

    RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
    roleHierarchy.setHierarchy("ROLE_SUPREME > ROLE_DEVELOPER > ROLE_ADMIN ");
    return roleHierarchy;

}

I hope it helped you.

Upvotes: 1

nAtxO Pi
nAtxO Pi

Reputation: 21

what do you think about this approach in ResourceServer?

   @Bean
    public RoleHierarchyImpl roleHierarchy() {
        RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
        roleHierarchy.setHierarchy("ROLE_SUPREME > ROLE_DEVELOPER ROLE_DEVELOPER > ROLE_ADMIN  ROLE_ADMIN > ROLE_USER")         return roleHierarchy;
    }


    @Bean
    public RoleHierarchyVoter roleVoter() {
        return new RoleHierarchyVoter(roleHierarchy());
    }


    @Bean
    public AffirmativeBased defaultOauthDecisionManager(RoleHierarchy roleHierarchy){ //

      List<AccessDecisionVoter> decisionVoters = new ArrayList<AccessDecisionVoter>();

      // webExpressionVoter
      OAuth2WebSecurityExpressionHandler expressionHandler = new OAuth2WebSecurityExpressionHandler();
      expressionHandler.setRoleHierarchy(roleHierarchy);
      WebExpressionVoter webExpressionVoter = new WebExpressionVoter();
      webExpressionVoter.setExpressionHandler(expressionHandler);
      decisionVoters.add(webExpressionVoter);
      decisionVoters.add(roleVoter());
      return new AffirmativeBased(decisionVoters);
    }

And

http
                .authorizeRequests()
                .accessDecisionManager(defaultOauthDecisionManager(roleHierarchy()))
                //etc...

It could be better structured and encapsulated but you know what i mean, don't you?... I think it works fine. I hope this will help you...

Upvotes: 2

Related Questions