@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(); }
@Test public void shouldReturnErrorIfPasswordNotSpecified() { when(authentication.getCredentials()).thenReturn(null); try { provider.authenticate(authentication); } catch (AuthenticationException e) { assertEquals("User or password not valid", e.getMessage()); } }
@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()); } }
/** Authentication test. */ public void doAuthTest( StaplerRequest req, StaplerResponse rsp, @QueryParameter String username, @QueryParameter String password) throws IOException, ServletException { // require the administrator permission since this is full of debug info. Hudson.getInstance().checkPermission(Hudson.ADMINISTER); StringWriter out = new StringWriter(); PrintWriter pw = new PrintWriter(out); ClassLoader ccl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); try { UserDetailsService uds = getAuthenticationProvider(); if (uds instanceof ActiveDirectoryUnixAuthenticationProvider) { ActiveDirectoryUnixAuthenticationProvider p = (ActiveDirectoryUnixAuthenticationProvider) uds; DesciprotrImpl descriptor = getDescriptor(); for (String domainName : domain.split(",")) { try { pw.println("Domain=" + domainName + " site=" + site); List<SocketInfo> ldapServers = descriptor.obtainLDAPServer(domainName, site, server); pw.println("List of domain controllers: " + ldapServers); for (SocketInfo ldapServer : ldapServers) { pw.println("Trying a domain controller at " + ldapServer); try { UserDetails d = p.retrieveUser( username, password, domainName, Collections.singletonList(ldapServer)); pw.println("Authenticated as " + d); } catch (AuthenticationException e) { e.printStackTrace(pw); } } } catch (NamingException e) { pw.println("Failing to resolve domain controllers"); e.printStackTrace(pw); } } } else { pw.println("Using Windows ADSI. No diagnostics available."); } } catch (Exception e) { e.printStackTrace(pw); } finally { Thread.currentThread().setContextClassLoader(ccl); } req.setAttribute("output", out.toString()); req.getView(this, "test.jelly").forward(req, rsp); }
/** * 权限验证 * * @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; }
@Test public void testCreateProxyWrapper() { AuthenticationException wrappedObject = new S4AuthenticationExceptionProxyCreatorForTest().create(mockAuthenticationException); Assert.assertNotNull(wrappedObject); Assert.assertNotNull(wrappedObject.getAuthentication()); Assert.assertTrue(wrappedObject.getAuthentication().getPrincipal().equals(MOCK_PRINCIPAL)); Assert.assertTrue( wrappedObject.getAuthentication().isAuthenticated() == MOCK_PRINCIPAL_IS_AUTHENTICATED); }
@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; }
/* * 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"); } }
/** ${@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()); } }
@SuppressWarnings("deprecation") @Override public void onAuthenticationFailure( HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { if (exception.getClass().isAssignableFrom(UnverifiedUserException.class)) { System.out.println(exception.getExtraInformation()); getRedirectStrategy() .sendRedirect( request, response, "/login/unverified?email=" + exception.getAuthentication().getName() + "&status=" + ((FingraphUser) exception.getExtraInformation()).getStatus()); } else if (exception.getClass().isAssignableFrom(PasswordMissmatchUserException.class)) { System.out.println(exception.getExtraInformation()); getRedirectStrategy().sendRedirect(request, response, "/login/form?error=100"); } else if (exception.getClass().isAssignableFrom(UnapprovalUserException.class)) { System.out.println(exception.getExtraInformation()); getRedirectStrategy().sendRedirect(request, response, "/login/form?error=200"); } else { super.onAuthenticationFailure(request, response, exception); } }
private boolean openIdAuthenticationSuccesfullButUserIsNotRegistered( AuthenticationException exception) { return exception instanceof UsernameNotFoundException && exception.getAuthentication() instanceof OpenIDAuthenticationToken && OpenIDAuthenticationStatus.SUCCESS.equals( (getOpenIdAuthenticationToken(exception)).getStatus()); }
@Override @Transactional public void onAuthenticationFailure( HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { // Wrong password or username if (exception instanceof BadCredentialsException) { MotechUser motechUser = motechUsersDao.findByUserName(exception.getAuthentication().getName()); int failureLoginLimit = settingService.getFailureLoginLimit(); if (motechUser != null && failureLoginLimit > 0) { int failureLoginCounter = motechUser.getFailureLoginCounter(); failureLoginCounter++; if (failureLoginCounter > failureLoginLimit && motechUser.isActive()) { motechUser.setUserStatus(UserStatus.BLOCKED); failureLoginCounter = 0; LOGGER.debug("User {} has been blocked", motechUser.getUserName()); } motechUser.setFailureLoginCounter(failureLoginCounter); motechUsersDao.update(motechUser); } if (motechUser != null && !motechUser.isActive()) { LOGGER.debug("Redirecting to " + userBlockedUrl); redirectStrategy.sendRedirect(request, response, userBlockedUrl); return; } } super.onAuthenticationFailure(request, response, exception); }
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 commence( HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { response.setHeader("WWW-Authenticate", this.headerValue); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()); }
@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 */ }
@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(); }
/** * Convenience method for logging an {@link AuthenticationException}. * * <p>This method will log the following exception types at the FINE level: * * <ul> * <li>{@link UsernameNotFoundException} * <li>{@link BadCredentialsException} * <li>{@link DisabledException} * </ul> * * All other exception types are logged at WARNING. */ protected void log(AuthenticationException ex) { Level l = Level.WARNING; if (ex instanceof UsernameNotFoundException || ex instanceof BadCredentialsException || ex instanceof DisabledException) { l = Level.FINE; } LOGGER.log(l, ex.getLocalizedMessage(), ex); }
@Before public void setUp() throws NoSuchMethodException { mockAuthentication = mock(Authentication.class); when(mockAuthentication.getPrincipal()).thenReturn(MOCK_PRINCIPAL); when(mockAuthentication.isAuthenticated()).thenReturn(MOCK_PRINCIPAL_IS_AUTHENTICATED); mockAuthenticationException = mock(AuthenticationException.class); when(mockAuthenticationException.getAuthentication()).thenReturn(mockAuthentication); }
@Override public void onAuthenticationFailure( HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { Authentication auth = exception.getAuthentication(); if (auth != null) { logger.info("username: " + auth.getName()); } super.onAuthenticationFailure(request, response, exception); }
@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 commence( HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { if (authException == null) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } else { final String exceptionCode = authenticationFailureHandler.getExceptionCode(authException.getClass()); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, exceptionCode); } }
@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 commence( HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { // if( authException instanceof InsufficientAuthenticationException) { // return; // } response.addHeader("Access-Control-Allow-Origin", "null"); response.addHeader("WWW-Authenticate", "Basic realm=\"" + getRealmName() + "\""); response.addHeader("Content-Type", "application/json"); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); PrintWriter writer = response.getWriter(); ObjectMapper mapper = new ObjectMapper(); ErrorInfo errorInfo = new ErrorInfo(HttpServletResponse.SC_UNAUTHORIZED, authException.getLocalizedMessage()); String jsonError = mapper.writeValueAsString(errorInfo); writer.println(jsonError); LOG.info("result = " + jsonError); }
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);*/ } } }
@Override public void onAuthenticationFailure( HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException, ServletException { logger.debug( "commencing RealAuthenticationFailureHandler because of {}", authenticationException.getClass()); AuthnRequestInfo authnRequestInfo = (AuthnRequestInfo) request.getSession().getAttribute(AuthnRequestInfo.class.getName()); if (authnRequestInfo == null) { logger.warn( "Could not find AuthnRequestInfo on the request. Delegating to nonSSOAuthnFailureHandler."); nonSSOAuthnFailureHandler.onAuthenticationFailure(request, response, authenticationException); return; } logger.debug("AuthnRequestInfo is {}", authnRequestInfo); request .getSession() .setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, authenticationException); CriteriaSet criteriaSet = new CriteriaSet(); criteriaSet.add(new EntityIDCriteria(idpConfiguration.getEntityID())); criteriaSet.add(new UsageCriteria(UsageType.SIGNING)); Credential signingCredential = null; try { signingCredential = credentialResolver.resolveSingle(criteriaSet); } catch (org.opensaml.xml.security.SecurityException e) { logger.warn("Unable to resolve signing credential for entityId", e); return; } Validate.notNull(signingCredential); AuthnResponseGenerator authnResponseGenerator = new AuthnResponseGenerator( signingCredential, idpConfiguration.getEntityID(), timeService, idService, idpConfiguration); EndpointGenerator endpointGenerator = new EndpointGenerator(); Response authResponse = authnResponseGenerator.generateAuthnResponseFailure( authnRequestInfo.getAssertionConsumerURL(), authnRequestInfo.getAuthnRequestID(), authenticationException); Endpoint endpoint = endpointGenerator.generateEndpoint( AssertionConsumerService.DEFAULT_ELEMENT_NAME, authnRequestInfo.getAssertionConsumerURL(), null); request.getSession().removeAttribute(AuthnRequestInfo.class.getName()); String relayState = request.getParameter("RelayState"); try { bindingAdapter.sendSAMLMessage( authResponse, endpoint, response, relayState, signingCredential); } catch (MessageEncodingException mee) { logger.error("Exception encoding SAML message", mee); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } }
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(); } }
private OpenIDAuthenticationToken getOpenIdAuthenticationToken( AuthenticationException exception) { return ((OpenIDAuthenticationToken) exception.getAuthentication()); }
@Override public void onAuthenticationFailure( HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { response.sendRedirect("/?error=" + exception.getMessage()); }