AccessDecisionManager how to add RoleVoter

First of all, I would like to ask if it is possible to access by default AccessDecisionManagerin the Java configuration (without using any xml file)?

Secondly, my problem looks like this. I want to add RoleVoterto my configuration, but I cannot figure out how to do this.

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{

   ...

   @Bean
   public RoleHierarchy roleHierarchy() {
      RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
      roleHierarchy.setHierarchy("ADMIN > USER");
      return roleHierarchy;
   }

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

My attempt was to add my AffirmativeBasedbean manager to HttpSecurityon authorizeRequests().accessDecisionManager(defaultAccessDecisionManager).

@Bean
public AffirmativeBased defaultAccessDecisionManager(RoleVoter roleVoter, AuthenticatedVoter authenticatedVoter, PreInvocationAuthorizationAdviceVoter preAdviceVoter){
    AffirmativeBased affirmativeBased = new AffirmativeBased(Arrays.asList(new WebExpressionVoter,(AccessDecisionVoter) roleVoter));
    affirmativeBased.setAllowIfAllAbstainDecisions(true);
    return affirmativeBased;
}

But it fails to vote because of a class WebExpressionConfigAttributethat always returns null by method getAttribute.

EDIT: I think I get it. My attemp was not so wrong, here is a little editingdefaultAccessDecisionManager

@Bean
public AffirmativeBased defaultAccessDecisionManager(RoleHierarchy roleHierarchy){
    WebExpressionVoter webExpressionVoter = new WebExpressionVoter();
    DefaultWebSecurityExpressionHandler expressionHandler = new DefaultWebSecurityExpressionHandler();
    expressionHandler.setRoleHierarchy(roleHierarchy);
    webExpressionVoter.setExpressionHandler(expressionHandler);
    return new AffirmativeBased(Arrays.asList((AccessDecisionVoter) webExpressionVoter));
}

defaultAccessDecisionManager HttpSecurity . - , ?

+4
1
http
.requestMatchers().antMatchers("/**")
.authorizeRequests()
    .antMatchers("/auth/**").permitAll()
    .antMatchers("/admin/only").hasRole("ADMIN")
    .anyRequest().authenticated()
    .withObjectPostProcessor(new ObjectPostProcessor<AffirmativeBased>() {
        @Override
        public AffirmativeBased postProcess(AffirmativeBased affirmativeBased) {
            affirmativeBased.getDecisionVoters().add(0, myAccessDecisionVoter1()); // add before WebExpressionVoter
            affirmativeBased.getDecisionVoters().add(myAccessDecisionVoter2()); // add after WebExpressionVoter
            return affirmativeBased;
        }
    });
0

Source: https://habr.com/ru/post/1533788/


All Articles