private void raiseExceptionForErrorCode(int code, NamingException exception) { String hexString = Integer.toHexString(code); Throwable cause = new ActiveDirectoryAuthenticationException(hexString, exception.getMessage(), exception); switch (code) { case PASSWORD_EXPIRED: throw new CredentialsExpiredException(messages.getMessage( "LdapAuthenticationProvider.credentialsExpired", "User credentials have expired"), cause); case ACCOUNT_DISABLED: throw new DisabledException(messages.getMessage( "LdapAuthenticationProvider.disabled", "User is disabled"), cause); case ACCOUNT_EXPIRED: throw new AccountExpiredException(messages.getMessage( "LdapAuthenticationProvider.expired", "User account has expired"), cause); case ACCOUNT_LOCKED: throw new LockedException(messages.getMessage( "LdapAuthenticationProvider.locked", "User account is locked"), cause); default: throw badCredentials(cause); } }
@Override public UsernamePasswordAuthenticationToken authenticate(ConnectionEnvironment connEnv, T authnCtx) throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException, CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException { checkEnteredCredentials(connEnv, authnCtx); MidPointPrincipal principal = getAndCheckPrincipal(connEnv, authnCtx.getUsername(), true); UserType userType = principal.getUser(); CredentialsType credentials = userType.getCredentials(); CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal, authnCtx); if (checkCredentials(principal, authnCtx, connEnv)) { recordPasswordAuthenticationSuccess(principal, connEnv, getCredential(credentials), credentialsPolicy); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, authnCtx.getEnteredCredential(), principal.getAuthorities()); return token; } else { recordPasswordAuthenticationFailure(principal, connEnv, getCredential(credentials), credentialsPolicy, "password mismatch"); throw new BadCredentialsException("web.security.provider.invalid"); } }
@Override public UserType checkCredentials(ConnectionEnvironment connEnv, T authnCtx) throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException, CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException { checkEnteredCredentials(connEnv, authnCtx); MidPointPrincipal principal = getAndCheckPrincipal(connEnv, authnCtx.getUsername(), false); UserType userType = principal.getUser(); CredentialsType credentials = userType.getCredentials(); CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal, authnCtx); if (checkCredentials(principal, authnCtx, connEnv)) { return userType; } else { recordPasswordAuthenticationFailure(principal, connEnv, getCredential(credentials), credentialsPolicy, "password mismatch"); throw new BadCredentialsException("web.security.provider.invalid"); } }
private <P extends CredentialPolicyType> void checkPasswordValidityAndAge(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, C credentials, P passwordCredentialsPolicy) { if (credentials == null) { recordAuthenticationFailure(principal, connEnv, "no stored credential value"); throw new AuthenticationCredentialsNotFoundException("web.security.provider.credential.bad"); } validateCredentialNotNull(connEnv, principal, credentials); if (passwordCredentialsPolicy == null) { return; } Duration maxAge = passwordCredentialsPolicy.getMaxAge(); if (maxAge != null) { MetadataType credentialMetedata = credentials.getMetadata(); XMLGregorianCalendar changeTimestamp = MiscSchemaUtil.getChangeTimestamp(credentialMetedata); if (changeTimestamp != null) { XMLGregorianCalendar passwordValidUntil = XmlTypeConverter.addDuration(changeTimestamp, maxAge); if (clock.isPast(passwordValidUntil)) { recordAuthenticationFailure(principal, connEnv, "password expired"); throw new CredentialsExpiredException("web.security.provider.password.bad"); } } } }
private void checkPasswordValidityAndAge(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, ProtectedStringType protectedString, MetadataType passwordMetadata, CredentialPolicyType passwordCredentialsPolicy) { if (protectedString == null) { recordAuthenticationFailure(principal, connEnv, "no stored password value"); throw new AuthenticationCredentialsNotFoundException("web.security.provider.password.bad"); } if (passwordCredentialsPolicy == null) { return; } Duration maxAge = passwordCredentialsPolicy.getMaxAge(); if (maxAge != null) { XMLGregorianCalendar changeTimestamp = MiscSchemaUtil.getChangeTimestamp(passwordMetadata); if (changeTimestamp != null) { XMLGregorianCalendar passwordValidUntil = XmlTypeConverter.addDuration(changeTimestamp, maxAge); if (clock.isPast(passwordValidUntil)) { recordAuthenticationFailure(principal, connEnv, "password expired"); throw new CredentialsExpiredException("web.security.provider.password.bad"); } } } }
/** * The method is used to extract the error message from the request * @param request The request that contains the exception and error message * @param key The key is used to find the exception attribute in the request. * @return Returns the error message that will be displayed to the user on the login page. */ private String getErrorMessage(final HttpServletRequest request, final String key) { final Exception exception = (Exception) request.getSession().getAttribute(key); String error = ""; if (exception instanceof BadCredentialsException || exception.getCause() instanceof NullPointerException || exception.getCause() instanceof IllegalArgumentException) { LOGGER.debug("Invalid username or password"); error = messageSource.getMessage("general.login.label.invalidcredentials", null, LocaleContextHolder.getLocale()); } else if (exception instanceof LockedException) { LOGGER.debug("User has been locked"); error = messageSource.getMessage("general.login.label.userlocked", null ,LocaleContextHolder.getLocale()); } else if(exception instanceof CredentialsExpiredException){ LOGGER.debug("User has been inactive"); error = messageSource.getMessage("general.login.label.userinactive", null ,LocaleContextHolder.getLocale()); } else { LOGGER.error("Unable to login due to unknown reasons"); LOGGER.error(exception.getMessage(), exception); error = messageSource.getMessage("general.login.label.unknownreason", null ,LocaleContextHolder.getLocale()); } return error; }
/** * Tests the status of the LDAP details and throws an appropriate exception. * * @param dirContextOperations * The context containing user data. * @param username * The username. * @throws AuthenticationException * if the status would prevent logging in */ private void checkAccountStatus(DirContextOperations dirContextOperations, String username) throws AuthenticationException { UserDetails ldapDetails = new LdapUserDetailsMapper() .mapUserFromContext(dirContextOperations, username, new ArrayList<GrantedAuthority>()); if (!ldapDetails.isEnabled()) { throw new DisabledException("LDAP account is disabled."); } if (!ldapDetails.isAccountNonLocked()) { throw new LockedException("LDAP account is locked."); } if (!ldapDetails.isCredentialsNonExpired()) { throw new CredentialsExpiredException("Credentials for LDAP account are expired."); } if (!ldapDetails.isAccountNonExpired()) { throw new AccountExpiredException("LDAP account is expired."); } }
@Override public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) { String token = authStore.getToken(requestResponseHolder.getRequest(), authHeaderName); if(logger.isDebugEnabled()){ logger.debug("load context user token : {}", token); } if(StringUtils.isBlank(token)){ return SecurityContextHolder.createEmptyContext(); } SecurityContext context = SecurityContextHolder.getContext(); Authentication authentication = null; try { authentication = jwtTokenService.createAuthentication(token); } catch(CredentialsExpiredException e){ cookieStorer.clear(requestResponseHolder.getRequest(), requestResponseHolder.getResponse(), authHeaderName); } if(authentication!=null){ context.setAuthentication(authentication); } return context; }
public void check(UserDetails user) { UserDetailsImpl userDetails = (UserDetailsImpl)user; if (userDetails == null) { throw new BadCredentialsException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } if (!userDetails.getIsConfirmed()) { throw new NotConfirmedException("Email is not confirmed", userDetails.getUsername()); } if (!user.isCredentialsNonExpired()) { logger.debug("User account credentials have expired"); throw new CredentialsExpiredException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.credentialsExpired", "User credentials have expired")); } }
private <P extends CredentialPolicyType> void checkPasswordValidityAndAge(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, C credentials, P passwordCredentialsPolicy) { if (credentials == null) { recordAuthenticationFailure(principal, connEnv, "no stored credential value"); throw new AuthenticationCredentialsNotFoundException("web.security.provider.credential.bad"); } validateCredentialNotNull(connEnv, principal, credentials); if (passwordCredentialsPolicy == null) { return; } Duration maxAge = passwordCredentialsPolicy.getMaxAge(); if (maxAge != null) { MetadataType credentialMetedata = credentials.getMetadata(); XMLGregorianCalendar changeTimestamp = MiscSchemaUtil.getChangeTimestamp(credentialMetedata); if (changeTimestamp != null) { XMLGregorianCalendar passwordValidUntil = XmlTypeConverter.addDuration(changeTimestamp, maxAge); if (clock.isPast(passwordValidUntil)) { recordAuthenticationFailure(principal, connEnv, "password expired"); throw new CredentialsExpiredException("web.security.provider.credential.expired"); } } } }
private void checkPasswordValidityAndAge(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, ProtectedStringType protectedString, MetadataType passwordMetadata, CredentialPolicyType passwordCredentialsPolicy) { if (protectedString == null) { recordAuthenticationFailure(principal, connEnv, "no stored password value"); throw new AuthenticationCredentialsNotFoundException("web.security.provider.password.bad"); } if (passwordCredentialsPolicy == null) { return; } Duration maxAge = passwordCredentialsPolicy.getMaxAge(); if (maxAge != null) { XMLGregorianCalendar changeTimestamp = MiscSchemaUtil.getChangeTimestamp(passwordMetadata); if (changeTimestamp != null) { XMLGregorianCalendar passwordValidUntil = XmlTypeConverter.addDuration(changeTimestamp, maxAge); if (clock.isPast(passwordValidUntil)) { recordAuthenticationFailure(principal, connEnv, "password expired"); throw new CredentialsExpiredException("web.security.provider.credential.expired"); } } } }
@Override public void check(UserDetails user) { if (!user.isCredentialsNonExpired()) { LOG.debug("User account credentials have expired"); throw new CredentialsExpiredException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.credentialsExpired", "User credentials have expired")); } if (user instanceof AuthUserDto) { AuthUserDto authUser = (AuthUserDto) user; if (authUser.isTempPassword()) { throw new TempCredentialsException("Temp credentials used to authenticate"); } } }
public void validateNonce(ConsumerDetails consumerDetails, long timestamp, String nonce) { if (System.currentTimeMillis() / 1000 - timestamp > getValidityWindowSeconds()) { throw new CredentialsExpiredException("Expired timestamp."); } NonceEntry entry = new NonceEntry(consumerDetails.getConsumerKey(), timestamp, nonce); synchronized (NONCES) { if (NONCES.contains(entry)) { throw new NonceAlreadyUsedException("Nonce already used: " + nonce); } else { NONCES.add(entry); } cleanupNonces(); } }
protected AuthResponse(Exception e){ super(e); this.setService(SERVICE_NAME); if (e instanceof AuthenticationException) { if (e instanceof UsernameNotFoundException) { this.setErrorCode(CodeUsernameNotFound); } else if (e instanceof DisabledException) { this.setErrorCode(CodeDisabled); } else if (e instanceof LockedException) { this.setErrorCode(CodeLocked); } else if (e instanceof BadCredentialsException) { this.setErrorCode(CodeBadCredentials); } else if (e instanceof CredentialsExpiredException) { this.setErrorCode(CodeCredentialsExpired); } else if (e instanceof BadCaptchaException) { this.setErrorCode(CodeBadCaptcha); } else if (e instanceof SmsProviderException){ this.setErrorCode(CodeSmsProvide); } else if (e instanceof UserExistException){ this.setErrorCode(CodeSmsProvide); } else if (e instanceof UnauthorizedException){ this.setErrorCode(CodeUnauthorized); } else { this.setErrorCode(CodeAuthenticationFailed); } } }
@Override public Authentication authenticate(final Authentication authentication) { final JwtAuthenticationToken authRequest = (JwtAuthenticationToken) authentication; final Jws<Claims> claimsJws = parserAndVerify(authRequest); if (claimsJws.getBody().getExpiration() == null) { throw new BadCredentialsException("Only temporary JWT supported"); } final String username = claimsJws.getBody().getSubject(); final UserDetails userDetails; try { userDetails = userDetailsService.loadUserByUsername(username); } catch (final UsernameNotFoundException notFound) { throw new BadCredentialsException("Bad credentials"); } if (!userDetails.isAccountNonLocked()) { throw new LockedException("User account is locked"); } if (!userDetails.isEnabled()) { throw new DisabledException("User is disabled"); } if (!userDetails.isAccountNonExpired()) { throw new AccountExpiredException("User account has expired"); } if (!userDetails.isCredentialsNonExpired()) { throw new CredentialsExpiredException("User credentials have expired"); } LOG.info("Successful JWT authentication for username={}", userDetails.getUsername()); return JwtAuthenticationToken.createAuthenticated(userDetails, authRequest.getDetails()); }
@ResponseStatus(HttpStatus.UNAUTHORIZED) @ExceptionHandler({AccessDeniedException.class, LockedException.class, DisabledException.class, CredentialsExpiredException.class}) @ResponseBody ResultDto handleUserException(HttpServletRequest req, Exception ex) { return new ResultDto(ex.getLocalizedMessage()); }
@Override public Board updateBoard(String id, BoardUpdateDto boardUpdateDto) { User user = getAuthorizedUser(); Board board = boardRepository.findOne(id); if (board != null) { if (!user.hasRole(UserRole.ADMIN) && !board.getOwner().equals(user) && !board.getUsers().contains(user)) { log.error("User {} does not have rights to alter board {}.", user.getUsername(), id); throw new AccessDeniedException("User is not allowed to alter board."); } board.setName(boardUpdateDto.getName()); board.setOwner(userService.loadUserByUsername(boardUpdateDto.getOwner().getUsername())); if (boardUpdateDto.getMembers() != null) { Set<User> members = new LinkedHashSet<>(); boardUpdateDto.getMembers().forEach(d -> { try { members.add(userService.loadUserByUsername(d.getUsername())); } catch (AccessDeniedException | LockedException | DisabledException | CredentialsExpiredException e) { log.warn(e.getMessage()); } }); board.setUsers(members); } boardRepository.save(board); } else { log.info("No board with given id {} found.", id); throw new BoardNotFoundException("Board with id " + id + " not found."); } return board; }
/** * Special-purpose method used for Web Service authentication based on javax.security callbacks. * * In that case there is no reasonable way how to reuse existing methods. Therefore this method is NOT part of the * AuthenticationEvaluator interface. It is mostly a glue to make the old Java security code work. */ public String getAndCheckUserPassword(ConnectionEnvironment connEnv, String enteredUsername) throws AuthenticationCredentialsNotFoundException, DisabledException, LockedException, CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException { MidPointPrincipal principal = getAndCheckPrincipal(connEnv, enteredUsername, true); UserType userType = principal.getUser(); CredentialsType credentials = userType.getCredentials(); if (credentials == null) { recordAuthenticationFailure(principal, connEnv, "no credentials in user"); throw new AuthenticationCredentialsNotFoundException("web.security.provider.invalid"); } PasswordType passwordType = credentials.getPassword(); SecurityPolicyType securityPolicy = principal.getApplicableSecurityPolicy(); PasswordCredentialsPolicyType passwordCredentialsPolicy = SecurityUtil.getEffectivePasswordCredentialsPolicy(securityPolicy); // Lockout if (isLockedOut(passwordType, passwordCredentialsPolicy)) { recordAuthenticationFailure(principal, connEnv, "password locked-out"); throw new LockedException("web.security.provider.locked"); } // Authorizations if (!hasAnyAuthorization(principal)) { recordAuthenticationFailure(principal, connEnv, "no authorizations"); throw new AccessDeniedException("web.security.provider.access.denied"); } // Password age checkPasswordValidityAndAge(connEnv, principal, passwordType.getValue(), passwordType.getMetadata(), passwordCredentialsPolicy); return getPassword(connEnv, principal, passwordType.getValue()); }
@Test public void test210UserGuybrushPasswordLoginGoodPasswordExpired() throws Exception { final String TEST_NAME = "test210UserGuybrushPasswordLoginGoodPasswordExpired"; TestUtil.displayTestTile(TEST_NAME); // GIVEN clock.overrideDuration("P2D"); ConnectionEnvironment connEnv = createConnectionEnvironment(); XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); try { // WHEN TestUtil.displayWhen(TEST_NAME); getAuthenticationEvaluator().authenticate(connEnv, getAuthenticationContext(USER_GUYBRUSH_USERNAME, getGoodPasswordGuybrush())); AssertJUnit.fail("Unexpected success"); } catch (CredentialsExpiredException e) { // This is expected // THEN TestUtil.displayThen(TEST_NAME); display("expected exception", e); assertExpiredException(e, USER_GUYBRUSH_USERNAME); } XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); PrismObject<UserType> userAfter = getUser(USER_GUYBRUSH_OID); display("user after", userAfter); assertFailedLogins(userAfter, 0); }
protected void translateException(PermissionDeniedDataAccessException e) throws DataAccessException { if (e.getCause() instanceof gov.va.hmp.vista.rpc.broker.protocol.BadCredentialsException) { throw new BadCredentialsException(e.getCause().getMessage()); } else if (e.getCause() instanceof VerifyCodeExpiredException) { throw new CredentialsExpiredException(e.getCause().getMessage()); } else if (e.getCause() instanceof RpcContextAccessDeniedException) { throw new AuthenticationServiceException(e.getCause().getMessage(), e.getCause()); } else if (e.getCause() instanceof ChangeVerifyCodeException) { throw new AuthenticationServiceException(e.getCause().getMessage(), e.getCause()); } else if (e.getCause() instanceof gov.va.hmp.vista.rpc.broker.protocol.LockedException) { throw new LockedException(e.getCause().getMessage()); } else{ throw e; } }
@Test public void testVerifyCodeExpired() { when(mockRpcTemplate.execute(any(ConnectionCallback.class), eq("vrpcb://" + RpcUriUtils.toAuthority(MOCK_VISTA_ID, MOCK_DIVISION, MOCK_ACCESS_CODE, MOCK_VERIFY_CODE, MOCK_REMOTE_ADDRESS, MOCK_REMOTE_HOSTNAME)))).thenThrow(new PermissionDeniedDataAccessException("",new VerifyCodeExpiredException())); try { s.login(MOCK_VISTA_ID, MOCK_DIVISION, MOCK_ACCESS_CODE, MOCK_VERIFY_CODE, null, null, MOCK_REMOTE_ADDRESS, MOCK_REMOTE_HOSTNAME); fail("expected a Spring Security BadCredentialsException"); } catch (CredentialsExpiredException e) { // NOOP } verify(mockRpcTemplate).execute(any(ConnectionCallback.class), eq("vrpcb://" + RpcUriUtils.toAuthority(MOCK_VISTA_ID, MOCK_DIVISION, MOCK_ACCESS_CODE, MOCK_VERIFY_CODE, MOCK_REMOTE_ADDRESS, MOCK_REMOTE_HOSTNAME))); }
@Test public void testVerifyCodeExpired() throws Exception { VerifyCodeExpiredException verifyCodeExpiredException = new VerifyCodeExpiredException(); ajaxAuthenticationFailureHandler.onAuthenticationFailure(mockRequest, mockResponse, new CredentialsExpiredException(verifyCodeExpiredException.getMessage(), verifyCodeExpiredException)); assertThat(mockResponse.getContentType(), equalTo("application/json")); assertThat(mockResponse.getStatus(), equalTo(HttpServletResponse.SC_UNAUTHORIZED)); assertJsonEquals("{\"apiVersion\":\"1\",\"success\":false,\"error\":{\"code\":\"" + AjaxAuthenticationFailureHandler.VERIFY_CODE_EXPIRED + "\",\"message\":\"" + verifyCodeExpiredException.getMessage() + "\"}}", mockResponse.getContentAsString()); }
public MotechLoginErrorHandler(String defaultFailureUrl, String userBlockedUrl, String changePasswordBaseUrl) { super(); this.userBlockedUrl = userBlockedUrl; Map<String, String> failureUrlMap = new HashMap<>(); failureUrlMap.put(CredentialsExpiredException.class.getName(), changePasswordBaseUrl); failureUrlMap.put(BadCredentialsException.class.getName(), defaultFailureUrl); failureUrlMap.put(LockedException.class.getName(), userBlockedUrl); setExceptionMappings(failureUrlMap); }
@Test public void shouldRedirectUserWithExpiredPassword() throws ServletException, IOException { AuthenticationException exception = new CredentialsExpiredException("Credentials expired"); exception.setAuthentication(authentication); MotechUser user = createUser(UserStatus.MUST_CHANGE_PASSWORD, 0); when(authentication.getName()).thenReturn("testUser"); when(motechUsersDao.findByUserName("testUser")).thenReturn(user); when(settingService.getFailureLoginLimit()).thenReturn(3); motechLoginErrorHandler.onAuthenticationFailure(request, response, exception); verify(response).sendRedirect(CHANGE_PASSWORD); }
@Test public void test210UserGuybrushPasswordLoginGoodPasswordExpired() throws Exception { final String TEST_NAME = "test210UserGuybrushPasswordLoginGoodPasswordExpired"; TestUtil.displayTestTitle(TEST_NAME); // GIVEN clock.overrideDuration("P2D"); ConnectionEnvironment connEnv = createConnectionEnvironment(); XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); try { // WHEN TestUtil.displayWhen(TEST_NAME); getAuthenticationEvaluator().authenticate(connEnv, getAuthenticationContext(USER_GUYBRUSH_USERNAME, getGoodPasswordGuybrush())); AssertJUnit.fail("Unexpected success"); } catch (CredentialsExpiredException e) { // This is expected // THEN TestUtil.displayThen(TEST_NAME); display("expected exception", e); assertExpiredException(e, USER_GUYBRUSH_USERNAME); } XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); PrismObject<UserType> userAfter = getUser(USER_GUYBRUSH_OID); display("user after", userAfter); assertFailedLogins(userAfter, 0); }
@Override public Authentication authenticate(final Authentication authentication) throws AuthenticationException { final JWTAuthentication jwtAuthentication = (JWTAuthentication) authentication; AuthContextUtils.execWithAuthContext(jwtAuthentication.getDetails().getDomain(), () -> { Pair<String, Set<SyncopeGrantedAuthority>> authenticated = dataAccessor.authenticate(jwtAuthentication); jwtAuthentication.setUsername(authenticated.getLeft()); jwtAuthentication.getAuthorities().addAll(authenticated.getRight()); return null; }); JwtClaims claims = jwtAuthentication.getClaims(); Long referenceTime = new Date().getTime(); Long expiryTime = claims.getExpiryTime(); if (expiryTime == null || (expiryTime * 1000L) < referenceTime) { dataAccessor.removeExpired(claims.getTokenId()); throw new CredentialsExpiredException("JWT is expired"); } Long notBefore = claims.getNotBefore(); if (notBefore == null || (notBefore * 1000L) > referenceTime) { throw new CredentialsExpiredException("JWT not valid yet"); } jwtAuthentication.setAuthenticated(true); return jwtAuthentication; }
@Override public Authentication authenticate(Authentication auth) throws AuthenticationException { String principal = (String) auth.getPrincipal(); String password = (String) auth.getCredentials(); //Transformacion de password a MD5 String passwordMD5 = getPasswordEncoder().encodePassword(password, null); UserDetails details = getUserDetailsService().loadUserByUsername(principal); if (principal == null || principal.trim().length() == 0) { throw new BadCredentialsException("Usuario obligatorio", null); } else if (password == null || password.trim().length() == 0) { throw new BadCredentialsException("Password obligatoria", null); } else if (details == null || !details.getPassword().equals(passwordMD5)) { throw new BadCredentialsException("Usuario y/o password no validos", null); } else if (!details.isEnabled()) { throw new DisabledException("La cuenta ha sido inhabilitada. Contacte con el administrador del sistema."); } else if (!details.isAccountNonLocked()) { throw new LockedException("La cuenta ha sido bloqueada. Contacte con el administrador del sistema."); } else if (!details.isAccountNonExpired()) { throw new AccountExpiredException("La cuenta ha caducado. Contacte con el administrador del sistema."); } else if (!details.isCredentialsNonExpired()) { throw new CredentialsExpiredException("La password ha caducado. Contacte con el administrador del sistema."); } try { usersService.updateDateAccess( auth.getPrincipal().toString() ); } catch (ValidationException | TransactionException e) { // TODO Auto-generated catch block e.printStackTrace(); } return new UsernamePasswordAuthenticationToken(details, passwordMD5, details.getAuthorities()); }
@Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { request.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception); // Lo faccio per compatibilità con li modo standard di gestire la cosa, ma non serve String username = request.getParameter("username"); request.setAttribute("username", username); try { if (exception instanceof BadCredentialsException) { request.setAttribute("passwordError", "passwordError"); userCredentialsRepository.incrementFailedAttempts(username); } else if (exception instanceof DisabledException) { request.setAttribute("userDisabled", "userDisabled"); } else if (exception instanceof CredentialsExpiredException) { request.setAttribute("credentialsExpiredException", "credentialsExpiredException"); request.getRequestDispatcher("/pwdChange").forward(request, response); return; } else if (exception instanceof TooManyFailedAttemptsException) { YadaUserCredentials yadaUserCredentials = userCredentialsRepository.findByUsername(username.toLowerCase(), new PageRequest(0, 1)).get(0); int lockMinutes = yadaConfiguration.getPasswordFailedAttemptsLockoutMinutes(); Date lastFailedTimestamp = yadaUserCredentials.getLastFailedAttempt(); if (lastFailedTimestamp!=null) { long minutesPassed = (long) Math.ceil((System.currentTimeMillis() - lastFailedTimestamp.getTime()) / 60000); long minutesLeft = lockMinutes - minutesPassed; request.setAttribute("lockoutMinutes", minutesLeft); } } else if (exception instanceof UsernameNotFoundException) { // ATTENZIONE, deve essere l'ultima della catena di if altrimenti le sottoclassi non vengono considerate request.setAttribute("usernameNotFound", "usernameNotFound"); request.setAttribute("password", request.getParameter("password")); } else { request.setAttribute("loginError", "loginError"); } } catch (Exception e) { log.error("Failed to handle authentication failure (ignored)", e); } boolean ajaxRequest = "XMLHttpRequest".equals(request.getHeader("X-Requested-With")); String failureUrl = ajaxRequest?failureUrlAjaxRequest:failureUrlNormalRequest; if (failureUrl == null) { log.debug("No failure URL set, sending 401 Unauthorized error"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication Failed: " + exception.getMessage()); } else { log.debug("Forwarding to " + failureUrl); request.getRequestDispatcher(failureUrl).forward(request, response); } }
private void assertExpiredException(CredentialsExpiredException e, String principal) { assertEquals("Wrong exception meessage (key)", "web.security.provider.password.bad", e.getMessage()); }
UsernamePasswordAuthenticationToken authenticate(ConnectionEnvironment connEnv, T authnCtx) throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException, CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException;
UserType checkCredentials(ConnectionEnvironment connEnv, T authnCtx) throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException, CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException;