List of usage examples for org.springframework.security.authentication UsernamePasswordAuthenticationToken getCredentials
public Object getCredentials()
From source file:fr.univrouen.poste.provider.DatabaseAuthenticationProvider.java
@Override @Transactional(noRollbackFor = BadCredentialsException.class) protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { UserDetails userDetails = null;//from ww w. j ava 2s . c o m logger.debug("Inside retrieveUser"); WebAuthenticationDetails wad = (WebAuthenticationDetails) authentication.getDetails(); String userIPAddress = wad.getRemoteAddress(); Boolean ipCanBeUsed4AuthAdminManager = this.isIpCanBeUsed4AuthAdminManager(userIPAddress); username = username.toLowerCase(); String password = (String) authentication.getCredentials(); if (!StringUtils.hasText(password) || !StringUtils.hasText(username)) { logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress); throw new BadCredentialsException("Merci de saisir votre email et mot de passe"); } String encryptedPassword = messageDigestPasswordEncoder.encodePassword(password, null); List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); Boolean enabled; try { TypedQuery<User> query = User.findUsersByEmailAddress(username, null, null); User targetUser = (User) query.getSingleResult(); if (targetUser.isLocked()) { throw new BadCredentialsException("Compte vrouill, merci de retenter d'ici quelques secondes."); } // authenticate the person String expectedPassword = targetUser.getPassword(); if (!StringUtils.hasText(expectedPassword)) { logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress); throw new BadCredentialsException("Aucun mot de passe pour " + username + " n'est enregistr dans la base, merci d'activer votre compte via le lien d'activation envoy par email. Contactez un administrateur si problme."); } if (!encryptedPassword.equals(expectedPassword)) { logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress); throw new BadCredentialsException("Email utilisateur ou mot de passe invalide."); } // restriction accs rseau if (!ipCanBeUsed4AuthAdminManager && (targetUser.getIsAdmin() || targetUser.getIsSuperManager() || targetUser.getIsManager())) { logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress); logger.warn("User " + username + " tried to access to his admin/manager/supermanager account from this IP " + userIPAddress); throw new BadCredentialsException( "Vous ne pouvez pas vous authentifier sur ce compte depuis cet accs rseau. Contactez un administrateur si problme."); } // restriction dates accs pour candidats et membres boolean isCurrentTimeOk4ThisCandidat = dateClotureChecker.isCurrentTimeOk4ThisCandidat(targetUser); boolean isCurrentTimeOk4ThisMembre = dateClotureChecker.isCurrentTimeOk4ThisMembre(targetUser); if ((targetUser.getIsCandidat() || targetUser.getIsMembre()) && !isCurrentTimeOk4ThisCandidat && !isCurrentTimeOk4ThisMembre) { if (targetUser.getIsCandidat() && !isCurrentTimeOk4ThisCandidat) { logger.warn("User " + username + " tried to access to his candidat account but the dateEndCandidat is < current time"); } if (targetUser.getIsMembre() && !isCurrentTimeOk4ThisMembre) { logger.warn("User " + username + " tried to access to his membre account but the dateEndMembre is < current time"); } logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress); throw new BadCredentialsException( "La date de clture des dpts est dpasse, vous ne pouvez maintenant plus accder l'application."); } userDetails = databaseUserDetailsService.loadUserByUser(targetUser); } catch (EmptyResultDataAccessException e) { logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress); throw new BadCredentialsException("Compte utilisateur et/ou mot de passe invalide"); } catch (EntityNotFoundException e) { logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress); throw new BadCredentialsException("Compte utilisateur et/ou mot de passe invalide"); } catch (NonUniqueResultException e) { logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress); throw new BadCredentialsException("Utilisateur non unique, contactez l'administrateur."); } logService.logActionAuth(LogService.AUTH_SUCCESS, username, userIPAddress); return userDetails; }
From source file:shiver.me.timbers.spring.security.UsernamePasswordStormpathAuthenticationRequestFactoryTest.java
@Test public void Can_create_a_username_and_password_stormpath_authentication_request() { final StormpathRequestBuilderFactory builderFactory = mock(StormpathRequestBuilderFactory.class); final String username = someString(); final UsernamePasswordAuthenticationToken authentication = mock(UsernamePasswordAuthenticationToken.class); final String password = someString(); final BasicAuthenticationOptions options = mock(BasicAuthenticationOptions.class); final BasicAuthenticationOptions optionsWithAccount = mock(BasicAuthenticationOptions.class); final UsernamePasswordRequestBuilder builder = mock(UsernamePasswordRequestBuilder.class); final UsernamePasswordRequestBuilder usernameBuilder = mock(UsernamePasswordRequestBuilder.class); final UsernamePasswordRequestBuilder passwordBuilder = mock(UsernamePasswordRequestBuilder.class); final UsernamePasswordRequestBuilder optionsBuilder = mock(UsernamePasswordRequestBuilder.class); final AuthenticationRequest expected = mock(AuthenticationRequest.class); // Given/*from w w w. j a va 2s . c om*/ given(authentication.getCredentials()).willReturn(password); given(builderFactory.options()).willReturn(options); given(options.withAccount()).willReturn(optionsWithAccount); given(builderFactory.builder()).willReturn(builder); given(builder.setUsernameOrEmail(username)).willReturn(usernameBuilder); given(usernameBuilder.setPassword(password)).willReturn(passwordBuilder); given(passwordBuilder.withResponseOptions(optionsWithAccount)).willReturn(optionsBuilder); given(optionsBuilder.build()).willReturn(expected); // When final AuthenticationRequest actual = new UsernamePasswordStormpathAuthenticationRequestFactory( builderFactory).create(username, authentication); // Then assertThat(actual, is(expected)); }
From source file:cn.net.withub.demo.bootsec.hello.security.CustomAuthenticationProvider.java
@Transactional @Override/*from ww w. ja v a 2 s .co m*/ public Authentication authenticate(Authentication authentication) throws AuthenticationException { UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication; String username = token.getName(); //??? //? UserDetails userDetails = null; if (username != null) { userDetails = userDetailsService.loadUserByUsername(username); } if (userDetails == null) { return null;//null?? //throw new UsernameNotFoundException("??/?"); } else if (!userDetails.isEnabled()) { throw new DisabledException("?"); } else if (!userDetails.isAccountNonExpired()) { throw new AccountExpiredException("?"); } else if (!userDetails.isAccountNonLocked()) { throw new LockedException("??"); } else if (!userDetails.isCredentialsNonExpired()) { throw new LockedException("?"); } //?? String encPass = userDetails.getPassword(); //authentication?credentials if (!md5PasswordEncoder.isPasswordValid(encPass, token.getCredentials().toString(), null)) { throw new BadCredentialsException("Invalid username/password"); } //? return new UsernamePasswordAuthenticationToken(userDetails, encPass, userDetails.getAuthorities()); }
From source file:org.taverna.server.master.identity.StrippedDownAuthProvider.java
@PerfLogged @Override/*from w w w .j a va 2 s .c o m*/ public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (!(authentication instanceof UsernamePasswordAuthenticationToken)) throw new IllegalArgumentException("can only authenticate against username+password"); UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication; // Determine username String username = (auth.getPrincipal() == null) ? "NONE_PROVIDED" : auth.getName(); UserDetails user; try { user = retrieveUser(username, auth); if (user == null) throw new IllegalStateException( "retrieveUser returned null - a violation of the interface contract"); } catch (UsernameNotFoundException notFound) { if (logger.isDebugEnabled()) logger.debug("User '" + username + "' not found", notFound); throw new BadCredentialsException("Bad credentials"); } // Pre-auth if (!user.isAccountNonLocked()) throw new LockedException("User account is locked"); if (!user.isEnabled()) throw new DisabledException("User account is disabled"); if (!user.isAccountNonExpired()) throw new AccountExpiredException("User account has expired"); Object credentials = auth.getCredentials(); if (credentials == null) { logger.debug("Authentication failed: no credentials provided"); throw new BadCredentialsException("Bad credentials"); } String providedPassword = credentials.toString(); boolean matched = false; synchronized (authCache) { AuthCacheEntry pw = authCache.get(username); if (pw != null && providedPassword != null) { if (pw.valid(providedPassword)) matched = true; else authCache.remove(username); } } // Auth if (!matched) { if (!passwordEncoder.matches(providedPassword, user.getPassword())) { logger.debug("Authentication failed: password does not match stored value"); throw new BadCredentialsException("Bad credentials"); } if (providedPassword != null) synchronized (authCache) { authCache.put(username, new AuthCacheEntry(providedPassword)); } } // Post-auth if (!user.isCredentialsNonExpired()) throw new CredentialsExpiredException("User credentials have expired"); return createSuccessAuthentication(user, auth, user); }
From source file:ph.fingra.statisticsweb.security.FingraphAnthenticationProvider.java
@SuppressWarnings("unused") @Override/*w ww . ja v a 2 s . c om*/ protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { // admin.properties values logger.debug("[adminEmail] {}", adminEmail); logger.debug("[adminName] {}", adminName); logger.debug("[adminPassword] {}", adminPassword); UserDetails loadedUser = null; try { logger.debug("retrieveUser {}", username); Member member = null; if (username.equals(adminEmail)) { member = new Member(); member.setEmail(adminEmail); member.setName(adminName); member.setPassword(adminPassword); member.setStatus(MemberStatus.ACTIVE.getValue()); member.setJoinstatus(MemberJoinstatus.APPROVAL.getValue()); member.setRole(MemberRole.ROLE_ADMIN.getValue()); } else { member = memberService.get(username); } if (member == null) { throw new UsernameNotFoundException("Not found user id"); } // lastlogin update if (member.getRole() == MemberRole.ROLE_USER.getValue()) { memberService.updateMemberLastLoginTime(member); } if (member.getRole() == MemberRole.ROLE_ADMIN.getValue()) { //logger.debug("passwordEncoder {}", adminPasswordEncoder); loadedUser = new FingraphUser(member, adminPasswordEncoder); } else { loadedUser = new FingraphUser(member); } logger.debug("userDetail is {}", loadedUser.toString()); } catch (UsernameNotFoundException notFound) { if (authentication.getCredentials() != null) { String presentedPassword = authentication.getCredentials().toString(); passwordEncoder.isPasswordValid(userNotFoundEncodedPassword, presentedPassword, null); } throw notFound; } catch (Exception repositoryProblem) { throw new AuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem); } if (loadedUser == null) { throw new AuthenticationServiceException( "UserDetailsService returned null, which is an interface contract violation"); } return loadedUser; }
From source file:org.bibsonomy.webapp.util.spring.security.rememberMeServices.LDAPRememberMeServices.java
@Override protected void onLoginSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication successfulAuthentication) { if (successfulAuthentication instanceof UsernamePasswordAuthenticationToken) { final UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) successfulAuthentication; final Object principal = token.getPrincipal(); if (principal instanceof UserAdapter) { final UserAdapter userDetails = (UserAdapter) principal; final String username = userDetails.getUsername(); final String ldapID = userDetails.getUser().getLdapId(); final String clearPassword = token.getCredentials().toString(); final int tokenLifetime = this.getTokenValiditySeconds(); final long expiryTime = this.calculateExpiryTime(tokenLifetime); final String signatureValue = this.makeTokenSignature( new String[] { Long.toString(expiryTime), username, ldapID, clearPassword }); this.setCookie( new String[] { username, ldapID, clearPassword, Long.toString(expiryTime), signatureValue }, tokenLifetime, request, response); if (log.isDebugEnabled()) { log.debug("Added remember-me cookie for user '" + username + "', expiry: '" + new Date(expiryTime) + "'"); }/*w ww .j av a2 s.c o m*/ } } }
From source file:org.cloudifysource.security.CloudifyDaoAuthenticationProvider.java
/** * Creates the final <tt>Authentication</tt> object which will be returned * from the <tt>authenticate</tt> method. * /*from ww w .j av a2 s. c o m*/ * @param authentication * the original authentication request token * @param user * the <tt>UserDetails</tt> instance returned by the configured * <tt>UserDetailsContextMapper</tt>. * @return the Authentication object for the fully authenticated user. */ protected Authentication createSuccessfulAuthentication( final UsernamePasswordAuthenticationToken authentication, final CloudifyUserDetails user) { logger.finest("starting createSuccessfulAuthentication"); final CustomAuthenticationToken customAuthToken = new CustomAuthenticationToken(user, authentication.getCredentials(), user.getAuthorities(), user.getAuthGroups()); customAuthToken.setDetails(authentication.getDetails()); return customAuthToken; }
From source file:org.egov.infra.config.security.authentication.provider.ApplicationAuthenticationProvider.java
@Override protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) { HashMap<String, String> authenticationCredentials = (HashMap<String, String>) authentication .getCredentials();//from ww w . j a v a 2 s. c om if (authenticationCredentials == null || !passwordEncoder .matches(authenticationCredentials.get(LOGIN_PASS_FIELD), userDetails.getPassword())) { throw new BadCredentialsException(messages.getMessage(BAD_CRED_MSG_KEY, BAD_CRED_DEFAULT_MSG)); } }