Spring Security AuthenticationFailureHandler与AuthenticationFailureEvent

can*_*bey 5 jsf spring spring-security

我正在使用spring-security 3.1.4,我有一些要求:

  • 监视身份验证是成功还是失败
    • 如果成功,则将用户常规信息放入会话属性中
    • 如果结果是失败,那么;
      • 确定失败原因(帐户已锁定,帐户已过期,凭据已过期,用户已禁用,登录失败尝试超过等)
      • 为咆哮组件生成登录失败消息驻留在login.xhtml中
      • 采取针对失败事件的操作,例如,对于错误的凭据,在db中增加登录失败尝试和/或重定向到页面,例如重新定义凭据

我已经研究并找到了三种解决方案:

  • 实现PhaseListener哪个草率的原因会在
    所有阶段事件中调用它:

public class LoginErrorPhaseListener implements PhaseListener {
  private static final long   serialVersionUID              = -404551400448242299L;

  private static final String MESSAGES_RESOURCE_BUNDLE_NAME = "msgs";
  private static final String ACCESS_DENIED_MESSAGE_KEY     = "accessDeniedMessage";
  private static final String BAD_CREDENTIALS_MESSAGE_KEY   = "badCredentialsMessage";

  @Override
  public void beforePhase(final PhaseEvent arg0) {
    Exception e = (Exception) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(WebAttributes.AUTHENTICATION_EXCEPTION);
      if (e instanceof BadCredentialsException) {
         FacesContext fc = FacesContext.getCurrentInstance();
         ResourceBundle messages = fc.getApplication().getResourceBundle(fc, MESSAGES_RESOURCE_BUNDLE_NAME);
         fc.getExternalContext().getSessionMap().put(WebAttributes.AUTHENTICATION_EXCEPTION, null);
         fc.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, messages.getString(ACCESS_DENIED_MESSAGE_KEY), messages.getString(BAD_CREDENTIALS_MESSAGE_KEY)));
      }
   }

   @Override
   public void afterPhase(final PhaseEvent arg0) {
   }

   @Override
   public PhaseId getPhaseId() {
      return PhaseId.RENDER_RESPONSE;
   }

}
Run Code Online (Sandbox Code Playgroud)
  • 其他是定制AuthenticationFailureHandlerAuthenticationSuccessHandler

public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

   @Inject
   private UserDao userDao;

   public CustomAuthenticationFailureHandler() {
   }

   public CustomAuthenticationFailureHandler(String defaultFailureUrl) {
      super(defaultFailureUrl);
   }

   @Override
   public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
      super.onAuthenticationFailure(request, response, exception);
      Class exceptionClazz = exception.getClass();

      if (exceptionClazz == UsernameNotFoundException.class) {

      }
      else if (exceptionClazz == AuthenticationCredentialsNotFoundException.class) {

      }
      else if (exceptionClazz == BadCredentialsException.class) {
         UserBean user = (UserBean) exception.getExtraInformation();
         if (user.getLoginAttempts() == 2) {
            userDao.updateUserStates(user.getUsername(), true, false, true, true);
            userDao.resetUserLoginFailedAttempts(user.getUsername());
         }
         else {
            userDao.incrementLoginFailedAttempts(user.getUsername());
         }
      }
      else if (exceptionClazz == AccountStatusException.class) {

      }
      else if (exceptionClazz == AuthenticationServiceException.class) {

      }
      else if (exceptionClazz == InsufficientAuthenticationException.class) {

      }
      else if (exceptionClazz == NonceExpiredException.class) {

      }
      else if (exceptionClazz == PreAuthenticatedCredentialsNotFoundException.class) {

      }
      else if (exceptionClazz == ProviderNotFoundException.class) {

      }
      else if (exceptionClazz == RememberMeAuthenticationException.class) {

      }
      else if (exceptionClazz == SessionAuthenticationException.class) {

      }
   }
}

public class CustomAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

   @Inject
   private UserDao userDao;

   @Override
   public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
      super.onAuthenticationSuccess(request, response, authentication);
      UserPersonalInfoBean activeUser = (UserPersonalInfoBean) authentication.getPrincipal();
      request.getSession().setAttribute("activeUser", activeUser);
      userDao.resetUserLoginFailedAttempts(activeUser.getUsername());
   }
}
Run Code Online (Sandbox Code Playgroud)
  • 我发现的最后一种方法是实现spring-context的 ApplicationListener

@Named
public class BadCredentialsListener implements ApplicationListener<AuthenticationFailureBadCredentialsEvent> {
   private static final long   serialVersionUID              = -404551400448242299L;

   private static final String MESSAGES_RESOURCE_BUNDLE_NAME = "msgs";
   private static final String ACCESS_DENIED_MESSAGE_KEY     = "accessDeniedMessage";
   private static final String BAD_CREDENTIALS_MESSAGE_KEY   = "badCredentialsMessage";

   @Override
   public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent event) {
      FacesContext fc = FacesContext.getCurrentInstance();
      ResourceBundle messages = fc.getApplication().getResourceBundle(fc, MESSAGES_RESOURCE_BUNDLE_NAME);
      fc.getExternalContext().getSessionMap().put(WebAttributes.AUTHENTICATION_EXCEPTION, null);
      fc.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, messages.getString(ACCESS_DENIED_MESSAGE_KEY), messages.getString(BAD_CREDENTIALS_MESSAGE_KEY)));
   }

}
Run Code Online (Sandbox Code Playgroud)

我的问题终于到了。我是一名初级开发人员,无法说明/想出哪种方法有效/有效地解决了我克服我的要求和所用技术(jsr330注入,jsf上下文等)的最佳方法。

我放弃了jsf PhaseListener解决方案,原因如上所述。实际上,spring-security访问和失败处理程序与PhaseListeners 类似,但效率更高,因为它们是在更特定的条件下调用的。必须根据异常的类型从异常中拾取更多特定事件。但是,我应该同意在定义它们时security-context.xml会提高安全模块的可读性。听AbstractAuthenticationFailureEvent儿童课对我来说真的很好。每个事件在垂直方向上都是彼此分离的,并且是干净的。另外,由于不推荐使用AuthenticationExceptiongetExtraInformationgetAuthentication方法,因此我无法找到另一种方法来访问失败的用户名AuthenticationFailureHandler.onAuthenticationFailure

因此,据您了解,我很困惑,欢迎您提出意见。

预先感谢您,问候

Oha*_*adR 0

我认为是否使用一种选项的决定取决于您的要求。

例如,使用处理程序的动机之一:处理程序获取请求和响应参数。因此,如果您想在某些情况下将用户重定向到某个页面(例如,如果帐户被锁定,并且您想向他显示不同的 HTML 页面) - 您应该使用处理程序。事件监听器不能(也不应该)重定向用户或更改流程。他们只是听众……