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

问题描述

我有一个使用 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();
        ...
    }

我想在每个异常上发送 cutom 响应代码,例如 UsernameNotFoundException 为 404,DisabledException 为 403 等.现在我的 spring 安全配置中只有 authentication-failure-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().

推荐答案

身份验证失败处理程序 :

Authentication failure handler :

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>

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

08-01 05:36