为什么不调用我的PreInvocationAuthorizationAdvice.before?

时间:2016-12-18 16:07:40

标签: java spring spring-security

我正在尝试通过引入PreInvocationAuthorizationAdvice将自己的授权机制实现到Spring中。这是我的代码:

我的SecurityContext:

@Configuration
@ComponentScan({"com.security_test"})
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityContext extends GlobalMethodSecurityConfiguration
{
    @Override
    protected AccessDecisionManager accessDecisionManager()
    {
        try {
            AffirmativeBased ab = (AffirmativeBased) super.accessDecisionManager();
            List<AccessDecisionVoter<? extends Object>> advs = ab.getDecisionVoters();
            List<AccessDecisionVoter<? extends Object>> toBeRemoved = new ArrayList<>();
            for (AccessDecisionVoter<? extends Object> adv : advs) {
                if (adv instanceof PreInvocationAuthorizationAdviceVoter) {
                    toBeRemoved.add(adv);
                }
            }
            for (AccessDecisionVoter<? extends Object> adv : toBeRemoved) {
                advs.remove(adv);
            }
            advs.add(new PreInvocationAuthorizationAdviceVoter(new MyPreInvocationAdvice()));
            return ab;
        }
        catch (ClassCastException ex) {
            ArrayList decisionVoters = new ArrayList();
            decisionVoters.add(new PreInvocationAuthorizationAdviceVoter(new MyPreInvocationAdvice()));
            return new AffirmativeBased(decisionVoters);
        }
    }
}

我的SecurityAdapter:

@Configuration
@EnableWebSecurity
public class SecurityAdapter extends WebSecurityConfigurerAdapter
{
    @Override
    protected void configure(HttpSecurity http)
        throws Exception
    {
        http
            .authorizeRequests()
            .anyRequest().permitAll();
        http
            .csrf()
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
    }
}

最后是MyPreInvocationAdvice

public class MyPreInvocationAdvice implements PreInvocationAuthorizationAdvice
{
    public MyPreInvocationAdvice()
    {
    }

    @Override
    public boolean before(Authentication authentication, MethodInvocation methodInvocation, PreInvocationAttribute preInvocationAttribute)
    {
        return true;
    }
}

此时我正在授权所有请求。但事实是,当我提出请求时,根本不会调用before方法。有人可以告诉我我在哪里弄错了吗?

1 个答案:

答案 0 :(得分:0)

我自己找到了答案,所以我可以在将来自己引用它,就在这里。

您的控制器需要@PreAuthorize("")注释。如果您以后不想在自己身上使用它,那么String值无关紧要(这将是您使用它的代码,因此如果您不想使用它,只需丢弃它)。

@RestController
@PreAuthorize("")
public class Controller
{
}