春季安全认证的异常处理

春季安全认证的异常处理

本文介绍了春季安全认证的异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用Spring Security的3.0.x的应用程序在那里,我有一个自定义的AuthenticationProvider

I have an app using Spring Security 3.0.x. There I have a custom AuthenticationProvider:

public class AppAuthenticationProvider implements AuthenticationProvider {
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        ...
        if (!check1()) throw new UsernameNotFoundException();
        if (!check2()) throw new DisabledException();
        ...
    }

我想每个异常的发送对自定义响应codeS,例如404 UsernameNotFoundException,403 DisabledException等等。现在我只是在我的春季安全配置认证失败的URL,所以我得到重定向到它在身份验证每个异常()。

I'd like to send cutom response codes on each exception, for example 404 for UsernameNotFoundException, 403 for DisabledException etc. For now I just have authentication-failure-url in my spring security configuration so I get redirect to it on each exception in authenticate().

推荐答案

验证失败处理程序:

public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
  super.onAuthenticationFailure(request, response, exception);
  if(exception.getClass().isAssignableFrom(UsernameNotFoundException.class)) {
    showMessage("BAD_CREDENTIAL");
  } else if (exception.getClass().isAssignableFrom(DisabledException.class)) {
    showMessage("USER_DISABLED");
  }
}

配置:

<bean id="customAuthenticationFailureHandler"
      class="com.apackage.CustomAuthenticationFailureHandler">
    <property name="defaultFailureUrl" value="/index.jsp"/>
</bean>
<security:http auto-config="true">
  <security:form-login default-target-url="/welcome.jsp" authentication-failure-handler-ref="customAuthenticationFailureHandler" />
</security:http>

这篇关于春季安全认证的异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 02:46