@Override
 public Response toResponse(AuthenticationException exception) {
   logger.debug("Exception: {}", exception.getMessage());
   return Response.status(Status.UNAUTHORIZED)
       .entity(exception.getMessage())
       .type("text/plain")
       .build();
 }
 @Override
 public void onAuthenticationFailure(
     HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
     throws IOException, ServletException {
   e.printStackTrace();
   System.out.println("FAIL " + e.getMessage());
   response.getWriter().print(e.getMessage());
   response.getWriter().flush();
 }
  /*
   * Método que captura el fallo de autenticación a través de una excepción
   * de tipo AuthenticactionException.
   * params:
   *-HttpServletRequest request: petiticón
   *-HttpServletResponse response: respuesta
   *-AuthenticationException: Causa del fallo de autenticación
   * return:
   */
  @Override
  public void onAuthenticationFailure(
      HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
      throws IOException, ServletException {

    String usuario = request.getParameter("j_username");
    logger.warn(
        "Falla de autenticacion. Usuario: " + usuario + ". Causa: " + exception.getMessage());

    if (exception instanceof LockedException) {

      if (exception.getMessage().equals("B")) {
        // Si está bloqueado por mantenimiento
        ManejadorMensajes.agregarMensaje(
            request,
            TipoMensaje.ADVERTENCIA,
            "El sistema de Policlínico Santa Clara.  "
                + "se encuentra en mantenimiento y estaremos de vuelta pronto. "
                + "Si presenta problemas, consulte al administrador de sistema");
      } else {
        // Si la sesión estaba activa
        ManejadorMensajes.agregarMensaje(
            request, TipoMensaje.ERROR, "Sesión de usuario activa. Ciérrela e ingrese nuevamente");
      }
      response.sendRedirect(request.getContextPath());
    }

    if (exception instanceof BadCredentialsException) { // Si hubo error de autenticación
      ManejadorMensajes.agregarMensaje(
          request, TipoMensaje.ERROR, "Falla de autenticación: Usuario o contraseña inválidos");
      response.sendRedirect(request.getContextPath());
    }

    if (exception instanceof AccountExpiredException) { // Si cuenta no está vigente
      ManejadorMensajes.agregarMensaje(
          request,
          TipoMensaje.ERROR,
          "Falla de autenticación: Usuario no vigente o contraseña expirada");
      response.sendRedirect(request.getContextPath());
    }

    if (exception instanceof CredentialsExpiredException) { // Si las credenciales expiraron
      Utils.borrarAtributo(request, "cambiocontrasena");
      Utils.borrarAtributo(request, "usuariocambio");

      Utils.registrarAtributo(request, "cambiocontrasena", "1");
      Utils.registrarAtributo(request, "usuariocambio", usuario);

      response.sendRedirect(request.getContextPath() + "/usuarios/cambiar_contrasena");
    }
  }
Example #4
0
  /** ${@inheritDoc} */
  @Override
  public User login(String username, String password) throws FailedToLoginException {
    try {
      // Authenticate the user
      authenticationService.authenticate(username, password);
      LOGGER.info("[{}] has successfully logged in", username);

      // Get the user and return it
      return this.loadUserByUsername(username);
    } catch (AuthenticationException e) {
      LOGGER.error(e.getMessage());
      throw new FailedToLoginException(e.getMessage());
    }
  }
 @Test
 public void shouldReturnErrorIfPasswordNotSpecified() {
   when(authentication.getCredentials()).thenReturn(null);
   try {
     provider.authenticate(authentication);
   } catch (AuthenticationException e) {
     assertEquals("User or password not valid", e.getMessage());
   }
 }
 @Override
 public void commence(
     HttpServletRequest request,
     HttpServletResponse response,
     AuthenticationException authException)
     throws IOException, ServletException {
   response.setHeader("WWW-Authenticate", this.headerValue);
   response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage());
 }
 public void commence(
     HttpServletRequest request,
     HttpServletResponse response,
     AuthenticationException authException)
     throws IOException, ServletException {
   if (authException instanceof InvalidOAuthParametersException) {
     response.sendError(400, authException.getMessage());
   } else if (authException.getCause() instanceof UnsupportedSignatureMethodException) {
     response.sendError(400, authException.getMessage());
   } else {
     StringBuilder headerValue = new StringBuilder("OAuth");
     if (realmName != null) {
       headerValue.append(" realm=\"").append(realmName).append('"');
     }
     response.addHeader("WWW-Authenticate", headerValue.toString());
     response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage());
   }
 }
 @Override
 public void onAuthenticationFailure(
     HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
     throws IOException, ServletException {
   response.setContentType("text/plain");
   response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
   ServletOutputStream outputStream = response.getOutputStream();
   outputStream.print(exception.getMessage());
   outputStream.close();
 }
  @Override
  public void onAuthenticationFailure(
      HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
      throws ServletException, IOException {
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

    PrintWriter writer = response.getWriter();
    writer.write(exception.getMessage());
    writer.flush();
  }
Example #10
0
 @Test
 public void shouldReturnErrorIfUserAndPasswordNotValidOrDontHaveAnyRoles() {
   when(authentication.getName()).thenReturn("my_username");
   when(authentication.getCredentials()).thenReturn("my_password");
   try {
     provider.authenticate(authentication);
   } catch (AuthenticationException e) {
     assertEquals("User or password not valid", e.getMessage());
   }
 }
 /**
  * 权限验证
  *
  * @param username
  * @param password
  * @return
  */
 private Response authentication(String username, String password) {
   try {
     Authentication authentication =
         authenticationManager.authenticate( //
             new UsernamePasswordAuthenticationToken(username, password));
     SecurityContextHolder.getContext().setAuthentication(authentication);
   } catch (AuthenticationException e) {
     return buildErrorResponse(Status.UNAUTHORIZED, e.getMessage());
   }
   return null;
 }
Example #12
0
  @RequestMapping(value = "/login", method = RequestMethod.GET)
  public ModelAndView login(
      HttpServletRequest request, HttpServletResponse response, HttpSession session) {
    final boolean debug = log.isDebugEnabled();

    ModelAndView result = new ModelAndView();

    // ...first check for an authentication object, if one exists we are already logged in...
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if (authentication != null
        && !(authentication instanceof AnonymousAuthenticationToken)
        && authentication.isAuthenticated()) {
      try {
        if (debug) log.debug("User has already been authenticated.  Redirecting to dashboard.");

        // Redirect to Dashboard.action for struts2 support
        response.sendRedirect("Dashboard.action");

        return result;
      } catch (IOException e) {
        log.warn(
            "Could not perform the redirect for an authenticated user, displaying login page instead");
      }
    }

    // ...we're dealing with an unauthenticated user, we're going to show the login form...
    AuthzSubject guestUser = authzSubjectManager.getSubjectById(AuthzConstants.guestId);

    // ...before we return, check for an error message...
    boolean loginError = request.getParameter("authfailed") != null;

    if (loginError) {
      if (session != null) {
        AuthenticationException ex =
            (AuthenticationException)
                session.getAttribute(
                    AbstractAuthenticationProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY);

        if (ex != null) {
          result.addObject("errorMessage", RequestUtils.message(request, ex.getMessage()));
        }
      }
    }

    result.addObject("guestUsername", (guestUser != null) ? guestUser.getName() : "guest");
    result.addObject("guestEnabled", (guestUser != null && guestUser.getActive()));

    // ...set a response header so we can identify the login page explicitly...
    response.setHeader("hq-requires-auth", "1");

    return result;
  }
  @Override
  public void commence(HttpServletRequest req, HttpServletResponse res, AuthenticationException e)
      throws IOException, ServletException {

    res.setContentType(MediaType.APPLICATION_JSON_VALUE);
    Result<Map<String, Object>> result = new Result<Map<String, Object>>();
    Meta meta = new Meta();
    meta.setMessage(e.getMessage());
    meta.setStatus(HttpStatus.UNAUTHORIZED);
    ErrorInfo errorInfo =
        new ErrorInfo(
            e.getMessage(),
            Integer.toString(org.apache.commons.httpclient.HttpStatus.SC_UNAUTHORIZED));
    meta.setErrorInfo(errorInfo);
    result.setMeta(meta);

    PrintWriter out = res.getWriter();

    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(Include.NON_EMPTY);
    out.print(mapper.writeValueAsString(result));
    out.close();
  }
  @Override
  public void onAuthenticationFailure(
      HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
      throws IOException, ServletException {
    if (RequestUtils.isAajaxRequest(request)) {

      response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

      PrintWriter writer = response.getWriter();
      writer.write(exception.getMessage());
      writer.flush();

    } else {
      super.onAuthenticationFailure(request, response, exception);
    }
  }
  @Override
  public void onAuthenticationFailure(
      HttpServletRequest request, HttpServletResponse response, AuthenticationException ae)
      throws IOException, ServletException {
    logger.info(" onAuthenticationFailure");
    logger.info("classes " + ae.getClass());

    // org.springframework.security.web.authentication.session.SessionAuthenticationException
    @SuppressWarnings("deprecation")
    UsernamePasswordAuthenticationToken user =
        (UsernamePasswordAuthenticationToken) ae.getAuthentication();
    logger.info("xxxxxxxxx1 " + ae.getMessage());
    logger.info("xxxxxxxxx2 " + ae.hashCode());
    logger.info("xxxxxxxxx3 " + ae.toString());
    // user contains required data
    // login/duplicate ==> Session exceeded
    // login/failure ==> invalid username or password
    if (user != null) response.sendRedirect("login/failure");
    else response.sendRedirect("login/duplicate");

    // Session exceeded
    /*  onAuthenticationFailure
    xxxxxxxxx1 Maximum sessions of 1 for this principal  exceeded
    xxxxxxxxx2 109033592
    xxxxxxxxx3 org.springframework.security.web.authentication.session.SessionAuthenticationException: Maximum sessions of 1 for this principal exceeded
    user null*/

    // invalid username or password
    /*onAuthenticationFailure
    xxxxxxxxx1 java.lang.NullPointerException
    xxxxxxxxx2 1637300018
    xxxxxxxxx3 org.springframework.security.authentication.AuthenticationServiceException: java.lang.NullPointerException
    user org.springframework.security.authentication.UsernamePasswordAuthenticationToken@5b97ec2: Principal: sdsd; Credentials: [PROTECTED]; Authenticated: false; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@0: RemoteIpAddress: 127.0.0.1; SessionId: C602C7B2DFF3458815F9640ACC750D7F; Not granted any authorities
     */

    // invalid password Only
    /*onAuthenticationFailure
     xxxxxxxxx1 Bad credentials
    xxxxxxxxx2 405682457
    xxxxxxxxx3 org.springframework.security.authentication.BadCredentialsException: Bad credentials
    user org.springframework.security.authentication.UsernamePasswordAuthenticationToken@8b9d3a1a: Principal: MCA000049; Credentials: [PROTECTED]; Authenticated: false; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@0: RemoteIpAddress: 127.0.0.1; SessionId: C602C7B2DFF3458815F9640ACC750D7F; Not granted any authorities
      */

  }
  public void onAuthenticationFailure(
      HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
      throws IOException, ServletException {

    if (defaultFailureUrl == null) {
      logger.debug("No failure URL set, sending 401 Unauthorized error");
      System.out.println("emtra por aquiiiiiiiiiiiiiii 1111");
      response.sendError(
          HttpServletResponse.SC_UNAUTHORIZED, "Authentication Failed: " + exception.getMessage());
    } else {
      if (forwardToDestination) {
        logger.debug("Forwarding to " + defaultFailureUrl);

        request.getRequestDispatcher(defaultFailureUrl).forward(request, response);
      } else {
        System.out.println("entra por aqui 222222222 + " + exception);
        request.getRequestDispatcher("/attempt").include(request, response);

        /*logger.debug("Redirecting to " + defaultFailureUrl);
        redirectStrategy.sendRedirect(request, response, defaultFailureUrl);*/
      }
    }
  }
Example #17
0
 public static void unsuccessfulAuthorization(
     HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) {
   if (StringUtils.isNotBlank(request.getHeader(PROXY_ENTITIES_CHAIN))) {
     response.setHeader(PROXY_ENTITIES_DETAILS, failed.getMessage());
   }
 }
 @Override
 public void onAuthenticationFailure(
     HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
     throws IOException, ServletException {
   response.sendRedirect("/?error=" + exception.getMessage());
 }
  public void onAuthenticationFailure(
      HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) {
    /** 次数限制 */
    HttpSession session = request.getSession();
    if (exception.getMessage().equals("密码不正确")) {
      String name =
          request.getParameter(
              UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY);
      UserAccount u = null;
      if (commonDAO.findByPropertyName(UserAccount.class, "loginname", name).size() > 0) {
        u = commonDAO.findByPropertyName(UserAccount.class, "loginname", name).get(0);
      }
      Integer tryCount =
          (Integer) session.getAttribute(name + "_" + TRY_MAX_COUNT) == null
              ? 1
              : (Integer) session.getAttribute(name + "_" + TRY_MAX_COUNT) + 1;
      if (tryCount > maxTryCount - 1) {
        // 锁定账户
        u.setNonLocked(false);
        commonDAO.update(u);
        LogEntity le = new LogEntity();
        le.setDate(DmDateUtil.Current());
        le.setType("0");
        le.setTitle("登录失败");
        le.setContent("用户名:" + u.getName() + "--登录失败,密码错误超过最大登录尝试次数,已被锁定");
        le.setUser(u.getName() + "(" + u.getLoginname() + "[" + u.getCode() + "])");
        le.setIp(getIpAddress(request));
        commonDAO.save(le);
        logger.info(le.getUser() + ">>" + le.getContent());
        exception = new AuthenticationServiceException("超过最大登录尝试次数" + maxTryCount + ",用户已被锁定");
        session.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);
        session.removeAttribute(name + "_" + TRY_MAX_COUNT);
      } else {
        session.setAttribute(name + "_" + TRY_MAX_COUNT, tryCount);
        exception =
            new BadCredentialsException(exception.getMessage() + ",剩余尝试次数" + (3 - tryCount));
        LogEntity le = new LogEntity();
        le.setDate(DmDateUtil.Current());
        le.setType("0");
        le.setTitle("登录失败");
        le.setContent("用户名:" + u.getName() + "--登录失败");
        le.setUser(u.getName() + "(" + u.getLoginname() + "[" + u.getCode() + "])");
        le.setIp(getIpAddress(request));
        commonDAO.save(le);
        logger.info(le.getUser() + ">>" + le.getContent());
      }
    }

    /** 次数限制结束------------------ */
    try {
      // 觉得默认跳转的地方
      if (defaultFailureUrl == null) {
        logger.debug("No failure URL set, sending 401 Unauthorized error");

        response.sendError(
            HttpServletResponse.SC_UNAUTHORIZED,
            "Authentication Failed: " + exception.getMessage());
      } else {
        saveException(request, exception);

        if (forwardToDestination) {
          logger.debug("Forwarding to " + defaultFailureUrl);

          request.getRequestDispatcher(defaultFailureUrl).forward(request, response);
        } else {
          logger.debug("Redirecting to " + defaultFailureUrl);
          redirectStrategy.sendRedirect(request, response, defaultFailureUrl);
        }
      }
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ServletException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }