【问题标题】:Customizing LockedException of spring security to send new status code to angular.js自定义 Spring Security 的 LockedException 以向 angular.js 发送新的状态码
【发布时间】:2016-05-09 11:52:22
【问题描述】:

我在前面使用 spring 4 + hibernate 4 + spring security (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();
}

请帮助我 - 我应该如何处理角端,以便我可以重定向到适当的页面?

【问题讨论】:

    标签: angularjs spring spring-security


    【解决方案1】:

    我觉得解决方法很简单,就是没注意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);
        }
    
       }
    }
    

    现在,由于我给出了不同的状态代码,我可以在前面轻松区分。希望对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 2015-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-07
      • 1970-01-01
      • 2022-11-05
      • 2014-11-11
      相关资源
      最近更新 更多