private SecurityUser authenticateByUserId(UserId userId) { User user = userService.findUserById(userId); if (user == null) { throw new UsernameNotFoundException("User not found by refresh token"); } UserCredentials userCredentials = userService.findUserCredentialsByUserId(user.getId()); if (userCredentials == null) { throw new UsernameNotFoundException("User credentials not found"); } if (!userCredentials.isEnabled()) { throw new DisabledException("User is not active"); } if (user.getAuthority() == null) throw new InsufficientAuthenticationException("User has no authority assigned"); UserPrincipal userPrincipal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail()); SecurityUser securityUser = new SecurityUser(user, userCredentials.isEnabled(), userPrincipal); return securityUser; }
@Override public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException { if (LOG.isTraceEnabled()) { LOG.trace("Login failed for user {}.", httpServletRequest.getParameter(SecurityConstants.USERNAME_PARAM)); } final LoginStatus status = new LoginStatus(false, false, null, e.getMessage()); if (e instanceof LockedException) { status.setErrorId("login.locked"); } else if (e instanceof DisabledException) { status.setErrorId("login.disabled"); } else if (e instanceof UsernameNotFoundException) { status.setErrorId("login.error"); } mapper.writeValue(httpServletResponse.getOutputStream(), status); }
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"); } }
/** * 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 UserDetails loadUserByUsername(final String username) { LOGGER.debug("Authenticating {}", username); final String lowercaseUsername = username.toLowerCase(); final Optional<User> loadedUser = userRepository.findUserByUsernameIgnoreCase(lowercaseUsername); return loadedUser.map(user -> { if (isNotBlank(user.getActivationCode())) { // ActivationCode of user is set so the account is not yet activated. throw new DisabledException("Given user is not yet activated."); } if (isNotBlank(user.getPasswordResetCode())) { // PasswordResetCode of user is set so the account is disabled till the password was reseted. throw new DisabledException("Given user has requested password reset."); } // Map authorities final List<SimpleGrantedAuthority> grantedAuthorities = user.getAuthorities().stream() .map(authority -> new SimpleGrantedAuthority(authority.getName())).collect(Collectors.toList()); // Return converted user return springSecurityUser(lowercaseUsername, user.getPassword(), grantedAuthorities); }).orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseUsername + " was not found")); }
/** * handle locked ? * * @param userId * @return */ protected AuthenticationException handlerLocked(String userId) { AuthUser user = authUserServ.load(userId); if (user.getErrorCount() >= 5) { Long dateTime = user.getStateTime().getTime(); // 1 DAY = 86 400 000 ms if(new Date().getTime()-dateTime <86400000){ // Locked user if input 6 error password user.setEnabled(0); authUserServ.add(user); return new DisabledException(messages.getMessage( "AccountStatusUserDetailsChecker.locked")); } }else{ // error count ++ user.setErrorCount(user.getErrorCount() + 1); // state time user.setStateTime(new Date()); } int onlyCount=6-user.getErrorCount(); authUserServ.add(user); return new BadCredentialsException(messages.getMessage( "AccountStatusUserDetailsChecker.onlyCount", new Object[] { onlyCount })); }
/** * Tests whether a {@link DisabledException} is thrown when the user is not * active. */ @Test(expected=DisabledException.class) public void authenticate_shouldThrowDisabledExceptionIfUserIsInactive() { // 1. Mock an authentication request object final String shogun2UserName = "user"; final String correctPassword = "correctPassword"; final User userToAuth = createUserMock(shogun2UserName, correctPassword); // set user as inactive userToAuth.setActive(false); // 2. Mock the auth request for the inactive user Authentication authRequest = mock(Authentication.class); when(authRequest.getName()).thenReturn(shogun2UserName); when(authRequest.getCredentials()).thenReturn(correctPassword); // 3. Mock the userDao when(userDao.findByAccountName(shogun2UserName)).thenReturn(userToAuth); // 4. Call the authenticate method with the mocked object to provoke // the expected DisabledException authProvider.authenticate(authRequest); }
@Test(expected = DisabledException.class) public void ensureLoginIsNotPossibleIfUserIsDeactivated() throws UnsupportedMemberAffiliationException, NamingException { Person person = TestDataCreator.createPerson(); person.setPermissions(Collections.singletonList(Role.INACTIVE)); Mockito.when(personService.getPersonByLogin(Mockito.anyString())).thenReturn(Optional.of(person)); Mockito.when(ldapUserMapper.mapFromContext(Mockito.eq(context))) .thenReturn(new LdapUser(person.getLoginName(), Optional.of(person.getFirstName()), Optional.of(person.getLastName()), Optional.of(person.getEmail()))); Mockito.when(ldapSyncService.syncPerson(Mockito.any(Person.class), Matchers.<Optional<String>>any(), Matchers.<Optional<String>>any(), Matchers.<Optional<String>>any())) .thenReturn(person); personContextMapper.mapUserFromContext(context, person.getLoginName(), null); }
@Override protected void onInitialize() { super.onInitialize(); // Vérification des retours d'auth pac4J HttpServletRequest request = ((ServletWebRequest) RequestCycle.get().getRequest()).getContainerRequest(); Exception exception = (Exception) request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); if (exception != null) { if (exception instanceof DisabledException) { getSession().error(getString("home.identification.classic.error.userDisabled")); } else if (exception instanceof AuthenticationServiceException) { LOGGER.error("Authentication failed", exception); getSession().error(getString("home.identification.error.badCredentials") + exception.getMessage()); } else { LOGGER.error("An unknown error occurred during the authentication process", exception); getSession().error(getString("home.identification.error.unknown")); } request.getSession().removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); } }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { log.debug("Prüfen, ob sich der Nutzer in der DB befindet..."); if (userService.findByLogin(authentication.getName().toLowerCase()) == null) { log.debug("Der Nutzer " + authentication.getName() + " befindet sich nicht in der DB."); throw new DisabledException(authentication.getName()); // muss eine AccountStatusException sein!! } log.debug("Der Nutzer " + authentication.getName() + " befindet sich in der DB."); return null; // danach wird Provider gefragt (ldapAuthentication) }
@Bean public AuthenticationFailureHandler authenticationFailureHandler() { ExceptionMappingAuthenticationFailureHandler failureHandler = new ExceptionMappingAuthenticationFailureHandler(); Map<String, String> failureUrlMap = new HashMap<>(); failureUrlMap.put(BadCredentialsException.class.getName(), LoginAuthenticationFailureHandler.PASS_ERROR_URL); failureUrlMap.put(CaptchaException.class.getName(), LoginAuthenticationFailureHandler.CODE_ERROR_URL); failureUrlMap.put(AccountExpiredException.class.getName(), LoginAuthenticationFailureHandler.EXPIRED_URL); failureUrlMap.put(LockedException.class.getName(), LoginAuthenticationFailureHandler.LOCKED_URL); failureUrlMap.put(DisabledException.class.getName(), LoginAuthenticationFailureHandler.DISABLED_URL); failureHandler.setExceptionMappings(failureUrlMap); return failureHandler; }
@Override public CurrentUser loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByUsername(username); if (!user.isEnabled()) throw new DisabledException(USER_IS_DISABLED); return new CurrentUser(user); }
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); } } }
private Authentication authenticateByUsernameAndPassword(UserPrincipal userPrincipal, String username, String password) { User user = userService.findUserByEmail(username); if (user == null) { throw new UsernameNotFoundException("User not found: " + username); } UserCredentials userCredentials = userService.findUserCredentialsByUserId(user.getId()); if (userCredentials == null) { throw new UsernameNotFoundException("User credentials not found"); } if (!userCredentials.isEnabled()) { throw new DisabledException("User is not active"); } if (!encoder.matches(password, userCredentials.getPassword())) { throw new BadCredentialsException("Authentication Failed. Username or Password not valid."); } if (user.getAuthority() == null) throw new InsufficientAuthenticationException("User has no authority assigned"); SecurityUser securityUser = new SecurityUser(user, userCredentials.isEnabled(), userPrincipal); return new UsernamePasswordAuthenticationToken(securityUser, null, securityUser.getAuthorities()); }
void verifyAccountStatus(Person user) { if (user.isLocked()) { throw new LockedException("Account is locked."); } if (!user.isEnabled()) { throw new DisabledException("Account is disabled."); } }
@Test public void authenticationFailureReturnsLoginStatusWithErrorInfoOnAccountDisabled() throws Exception { final MockHttpServletRequest request = AuthenticationSuccessTest.request(); final MockHttpServletResponse response = AuthenticationSuccessTest.response(); final String msg = "Account is disabled."; failure.onAuthenticationFailure(request, response, new DisabledException(msg)); final LoginStatus status = mapper.readValue(response.getContentAsString(), LoginStatus.class); assertFalse(status.isSuccess()); assertFalse(status.isLoggedIn()); assertNull(status.getUsername()); assertEquals(msg, status.getErrorMessage()); assertEquals("login.disabled", status.getErrorId()); }
@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; }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication; String username = String.valueOf(auth.getPrincipal()); String password = String.valueOf(auth.getCredentials()); String passwordHash = DigestUtils.shaHex(password); // Log the default authentication request log.info("username:" + username); // Use the username to load the data for the user, including authorities and password. UserDetails user = userDetailsService.loadUserByUsername(username); // Check if account is enabled if (!user.isEnabled()) { throw new DisabledException("This user account is disabled"); } // Check the passwords match. if (!user.getPassword().equals(passwordHash)) { throw new BadCredentialsException("Bad Credentials"); } // Return an authenticated token, containing user data and authorities return new DefaultUsernamePasswordAuthenticationToken( user, // principal null, // credentials user.getAuthorities() // authorities ); }
private boolean checkCredentials(MidPointPrincipal principal, T authnCtx, ConnectionEnvironment connEnv) { UserType userType = principal.getUser(); CredentialsType credentials = userType.getCredentials(); if (credentials == null || getCredential(credentials) == null) { recordAuthenticationFailure(principal, connEnv, "no credentials in user"); throw new AuthenticationCredentialsNotFoundException("web.security.provider.invalid"); } CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal, authnCtx); // Lockout if (isLockedOut(getCredential(credentials), credentialsPolicy)) { recordAuthenticationFailure(principal, connEnv, "password locked-out"); throw new LockedException("web.security.provider.locked"); } if (suportsAuthzCheck()) { // Authorizations if (!hasAnyAuthorization(principal)) { recordAuthenticationFailure(principal, connEnv, "no authorizations"); throw new DisabledException("web.security.provider.access.denied"); } } // Password age checkPasswordValidityAndAge(connEnv, principal, getCredential(credentials), credentialsPolicy); return passwordMatches(connEnv, principal, getCredential(credentials), authnCtx); }
/** * 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()); }
private void loginJackGoodPasswordExpectDenied(final String TEST_NAME, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { display("now", clock.currentTimeXMLGregorianCalendar()); ConnectionEnvironment connEnv = createConnectionEnvironment(); XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); // WHEN TestUtil.displayWhen(TEST_NAME); try { getAuthenticationEvaluator().authenticate(connEnv, getAuthenticationContext(USER_JACK_USERNAME, getGoodPasswordJack())); AssertJUnit.fail("Unexpected success"); } catch (DisabledException e) { // This is expected // THEN TestUtil.displayThen(TEST_NAME); display("expected exception", e); // this is important. The exception should give no indication whether the password is // good or bad assertDisabledException(e, USER_JACK_USERNAME); } PrismObject<UserType> userAfter = getUser(USER_JACK_OID); display("user after", userAfter); assertFailedLogins(userAfter, 0); }
@Override public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException { IGroupedUser<?> user = getUserByUsername(userName); if (user == null) { throw new UsernameNotFoundException("CoreJpaUserDetailsServiceImpl: User not found: " + userName); } if (!user.isActive()) { throw new DisabledException("User is disabled"); } Pair<Set<GrantedAuthority>, Set<Permission>> authoritiesAndPermissions = getAuthoritiesAndPermissions(user); Collection<? extends GrantedAuthority> expandedGrantedAuthorities = roleHierarchy.getReachableGrantedAuthorities(authoritiesAndPermissions.getLeft()); addCustomPermissionsFromAuthorities(expandedGrantedAuthorities, authoritiesAndPermissions.getRight()); addPermissionsFromAuthorities(expandedGrantedAuthorities, authoritiesAndPermissions.getRight()); Collection<Permission> expandedReachablePermissions = permissionHierarchy.getReachablePermissions(authoritiesAndPermissions.getRight()); // In any case, we can't pass an empty password hash to the CoreUserDetails CoreUserDetails userDetails = new CoreUserDetails(user.getUserName(), StringUtils.hasText(user.getPasswordHash()) ? user.getPasswordHash() : EMPTY_PASSWORD_HASH, user.isActive(), true, true, true, expandedGrantedAuthorities, expandedReachablePermissions); return userDetails; }
@Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { ServletContext ctx = request.getSession().getServletContext(); String contextPath = ctx.getContextPath(); if (exception instanceof DisabledException) { response.sendRedirect(contextPath + redirectPathForDisabledUser); } else { response.sendRedirect(contextPath + redirectPathLoginError); } }
@Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { RequestDispatcher dispatcher = request.getRequestDispatcher(loginUrl); if (exception instanceof UsernameNotFoundException) { request.setAttribute("error", "用户名不存在!"); } else if (exception instanceof DisabledException) { request.setAttribute("error", "用户已被禁用!"); } else if (exception instanceof BadCredentialsException) { request.setAttribute("error", "用户名或密码错误!"); } else { request.setAttribute("error", "登陆失败!"); } dispatcher.forward(request, response); }
@Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { String errorMessage = "Authentication failed: " + exception.getLocalizedMessage(); if (exception instanceof DisabledException) { errorMessage = "Authentication failed: " + ApplicationErrorCodes.MLDS_ERR_AUTH_DEREGISTERED + " " + exception.getLocalizedMessage(); } response.sendError(HttpServletResponse.SC_UNAUTHORIZED, errorMessage); }
@Override public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException { if (e instanceof DisabledException) { httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN); httpServletResponse.getWriter().print(USER_DISABLED); } else { httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); httpServletResponse.getWriter().print(AUTHENTICATION_FAILED); } httpServletResponse.getWriter().flush(); }
@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()); }