gpt4 book ai didi

authentication - Spring security 验证异常处理

转载 作者:行者123 更新时间:2023-12-04 00:01:49 26 4
gpt4 key购买 nike

我有一个使用 Spring Security 3.0.x 的应用程序。我有一个自定义 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,所以我在 authentication 中的每个异常上都重定向到它()。

最佳答案

身份验证失败处理程序:

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>

关于authentication - Spring security 验证异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12731144/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com