当accessDecision.decide()抛出AccessDeniedException时,为什么不重定向到/ login?

时间:2016-12-17 15:29:41

标签: spring-security

我有一个像这样的自定义accessDecisionManager:

@Component
public class CustomAccessDecisionManager implements AccessDecisionManager {

    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
            throws AccessDeniedException, InsufficientAuthenticationException {

        LogManager.getLogger("CustomAccessDecisionManager").info("decide invoke");

        if (configAttributes == null) {
            return;
        }

        if (configAttributes.size() <= 0) {
            return;
        }

        Iterator<ConfigAttribute> authorities = configAttributes.iterator();
        String needAuthority = null;

        while(authorities.hasNext()) {
            ConfigAttribute authority = authorities.next();

            if (authority == null || (needAuthority = authority.getAttribute()) == null) {
                continue;
            }

            LogManager.getLogger("CustomAccessDecisionManager").info("decide == " + needAuthority);

            for (GrantedAuthority ga : authentication.getAuthorities()) {
                if (needAuthority.equals(ga.getAuthority().trim())) {
                    return;
                }
            }
        }
        throw new AccessDeniedException("No Authority");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        // TODO Auto-generated method stub
        return true;
    }
}

这是工作,并抛出一个AccessDeniedException,但页面直接显示异常,为什么不跳转到登录页面?

我在ExceptionTranslationFilter:

之前添加了自定义securityInterceptor
@Override
    protected void configure(HttpSecurity http) throws Exception {

        http.addFilterBefore(customFilterSecurityInterceptor(), ExceptionTranslationFilter.class);

    }

1 个答案:

答案 0 :(得分:1)

  1. 您应该在ExceptionTranslationFilter之后添加过滤器,ExceptionTranslationFilter将在其后捕获异常,然后决定要做什么。

  2. ExceptionTranslationFilter将处理两种例外,AuthenticationExceptionAccessDeniedException

  3. AuthenticationException - 这将发送开始身份验证(例如重定向到登录页面); AccessDeniedException - 这将发送到Access Denied Handler(除了匿名,这将发送以启动身份验证)。

    所以,如果你想重定向到loginPage,只是抛出异常扩展Authentication(这样好吗?),或者你可以处理访问被拒绝处理程序中的AccessDeniedException