我已经使用Spring Boot和Spring MVC开发了单页Web应用程序。我正在使用Spring Security和JWT对用户进行身份验证。我已经编写了一个自定义的AuthenticationFailureHandler,它可以工作,但是我想知道如何控制引发异常时用户重定向到的URL。我的AuthenticationFailureHandler看起来像这样:
public class JwtAuthenticationFailureHandler implements AuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
response.sendError(HttpStatus.UNAUTHORIZED.value(), exception.getMessage());
}
}
当JWT到期时,应用程序将引发AccountExpiredException,将执行AuthenticationFailureHandler.onAuthenticationFailure方法,并将用户重定向到登录页面:
http://localhost:8080/login?sessionExpired=true
这一切都很好,但是我不知道sessionExpired = true查询字符串是如何生成的,我想对其进行一些控制。过去我曾经使用过像这样的ExceptionMappingAuthenticationFailureHandlers:
Map<String, String> mappings = new HashMap<>();
mappings.put(BadCredentialsException.class.getCanonicalName(), BAD_CREDENTIALS_EXCEPTION_URL);
mappings.put(AccountExpiredException.class.getCanonicalName(), ACCOUNT_EXPIRED_EXCEPTION_URL);
mappings.put(CredentialsExpiredException.class.getCanonicalName(), CREDENTIALS_EXPIRED_EXCEPTION_URL);
mappings.put(DisabledException.class.getCanonicalName(), ACCOUNT_INACTIVE_EXCEPTION_URL);
mappings.put(LockedException.class.getCanonicalName(), ACCOUNT_LOCKED_EXCEPTION_URL);
mappings.put(ValidationException.class.getCanonicalName(), VALIDATION_EXCEPTION_URL);
ExceptionMappingAuthenticationFailureHandler exceptionMappingAuthenticationFailureHandler = new ExceptionMappingAuthenticationFailureHandler();
exceptionMappingAuthenticationFailureHandler.setExceptionMappings(mappings);
因此,基于上述各种例外情况,我希望能够重定向到以下URL:
http://localhost:8080/login?error
http://localhost:8080/login?accountexpired
http://localhost:8080/login?credentialsexpired
http://localhost:8080/login?accountlocked
http://localhost:8080/login?accountinactive
http://localhost:8080/login?validationerror
我不确定谁用response.sendError做到这一点,而且我不知道sessionExpired = true查询字符串是如何生成的。我曾尝试抛出不同的异常,但URL从未改变。
我有几个问题。
>使用HttpServletResponse.sendError时是否可以控制URL,否则,可以使用ExceptionMappingAuthenticationFailureHandler.sendRedirect设置HttpStatus代码吗?答案 0 :(得分:0)
为什么不尝试使用response.sendRedirect:
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
final HttpSession session = request.getSession(false);
if (session != null) {
request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);
}
//here the logic to get the error type of the exception
String errorMessage = ????
redirectStrategy.sendRedirect(request, response,
"http://localhost:8080/login?" + errorMessage);
}