我正在使用spring 4 +休眠4 + spring安全性(RESTFull Webservice API),并且在前端使用了angular。(这是非常新的)。
我的失败处理程序如下:
@Component
public class AuthFailure extends SimpleUrlAuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
}
如果我的请求失败,我将得到预期的401响应。现在,我想添加AccountLocked和CredentialsExpiredException功能。当我返回“用户”时,我正在适当地设置“假”。同样,我的确收到状态为401的回复。
return new User(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, AuthorityUtils.NO_AUTHORITIES);
因为我总是得到401并且在响应内没有得到任何用户对象(或者可能不知道如何获取它),所以在前端,我无法确定这是由于凭据错误或帐户被锁定还是凭据过期而导致的。我想重定向到另一个页面。我还尝试捕获异常并尝试转发不同的状态,但似乎没有遇到此代码。我总是得到401。
@ExceptionHandler(LockedException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public ModelAndView handleLockedException(Exception e) {
logger.error("Exception occurred => " + e.getMessage());
return new ErrorResponse(HttpStatus.BAD_REQUEST.value(), e.getMessage(), "Spring security exception").asModelAndView();
}
请帮助我-我应该如何处理弯角末端,以便可以重定向到适当的页面?
我认为解决方案非常简单,只是没有注意AuthFailure方法参数。修改了我的AuthFailuar,如下所示:
@Component
public class AuthFailure extends SimpleUrlAuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
if (exception instanceof LockedException) {
response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
}else if {
....
} else {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
}
}
现在,由于我给出了不同的状态代码,因此我可以轻松地在前端进行区分。希望对某人有帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句