首先,我想问一下,如果可以在Java配置中访问默认的AccessDecisionManager
(不使用任何xml文件)?
中学,我的问题看起来像那样。我想在我的配置中添加RoleVoter
,但我无法弄清楚如何操作。
@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);
}
我的尝试是AffirmativeBased
将HttpSecurity
经理bean添加到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;
}
但是在投票时它失败了,因为WebExpressionConfigAttribute
类总是在getAttribute
方法上返回null。
编辑:我想我弄清楚了。我的尝试不是很错,这里很少编辑defaultAccessDecisionManager
@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
对象中。有谁知道如何在全球范围内做到这一点?
答案 0 :(得分:0)
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;
}
});