【发布时间】:2019-05-21 08:01:39
【问题描述】:
我想使用内置的 Spring @PreAuthorize 注释和 hasRole、hasAnyRole 等,但是让 Spring 类调用我的实现来确定它是否应该为真/假。我该怎么做?
WebSecurityConfigurerAdapter 中是否有我可以覆盖的配置?
我需要实现SecurityExpressionRoot 类吗?如果是这样,我在哪里告诉它使用我的?
我尝试覆盖访问决策管理器并添加我自己的选民,但即使它调用我的方法并且我返回 true(它是一个 AffirmativeBased 管理器),它仍然转到 SecurityExpressionRoot.hasAnyRole() 然后返回 false .
public class MyDecisionVoter implements AccessDecisionVoter<Object>
{
@Override
public boolean supports(ConfigAttribute attribute)
{
//We want to always be called
return true;
}
@Override
public boolean supports(Class<?> clazz)
{
//We want to always be called
return true;
}
@Override
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes)
{
//For testing purposes
return ACCESS_GRANTED;
}
}
经理
public class MyAffirmativeBasedDecisionManager extends AffirmativeBased
{
public MyAffirmativeBasedDecisionManager(List<AccessDecisionVoter<?>> decisionVoters)
{
super( decisionVoters );
}
@Override
public boolean supports(Class<?> clazz)
{
for ( AccessDecisionVoter<?> voter : this.getDecisionVoters() )
{
if ( voter.supports( clazz ) )
{
return true;
}
}
return false;
}
}
配置
@EnableWebSecurity
@EnableGlobalMethodSecurity( prePostEnabled = true )
public class MyConfig extends WebSecurityConfigurerAdapter
{
@Override
protected void configure(HttpSecurity http) throws Exception
{
//Turn on OAuth
http.authorizeRequests()
.anyRequest()
.authenticated()
.accessDecisionManager( createDecisionManager() );
}
private AccessDecisionManager createDecisionManager()
{
List<AccessDecisionVoter<? extends Object>> decisionVoters = new ArrayList<>();
ExpressionBasedPreInvocationAdvice expressionAdvice = new ExpressionBasedPreInvocationAdvice();
expressionAdvice.setExpressionHandler( new DefaultMethodSecurityExpressionHandler() );
decisionVoters.add( new MyDecisionVoter() );
decisionVoters.add( new PreInvocationAuthorizationAdviceVoter( expressionAdvice ) );
decisionVoters.add( new RoleVoter() );
decisionVoters.add( new AuthenticatedVoter() );
return new MyAffirmativeBasedDecisionManager( decisionVoters );
}
}
这应该让他们进来,但它会失败并出现 403:
@GetMapping( "shouldallow" )
@ResponseBody
@PreAuthorize( "hasRole('ROLE_NOT_EXIST')" )
public String shouldAllow()
{
return "should allow";
}
【问题讨论】:
标签: java spring spring-boot spring-security roles