List of usage examples for org.springframework.security.authentication UsernamePasswordAuthenticationToken getCredentials
public Object getCredentials()
From source file:org.encuestame.core.security.web.EnMeUsernameProvider.java
@Override protected void additionalAuthenticationChecks(UserDetails userDetails, final UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { Object salt = null;/*from w ww. j a v a 2 s . c om*/ if (this.saltSource != null) { salt = this.saltSource.getSalt(userDetails); } final EnMeUserAccount detailsDataAccount = (EnMeUserAccount) userDetails; if (log.isDebugEnabled()) { log.debug("detailsDataAccount " + detailsDataAccount.toString()); } if (!detailsDataAccount.isSocialCredentials()) { log.debug("SOCIAL CREDENTIALS OFF"); if (authentication.getCredentials() == null) { logger.debug("Authentication failed: no credentials provided"); throw new BadCredentialsException(messages .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } String presentedPassword = authentication.getCredentials().toString(); if (!passwordEncoder.isPasswordValid(userDetails.getPassword(), presentedPassword, salt)) { logger.debug("Authentication failed: password does not match stored value"); throw new BadCredentialsException(messages .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } } else { if (log.isInfoEnabled()) { log.info("SOCIAL CREDENTIALS ON"); } } }
From source file:org.fao.geonet.kernel.security.ecas.ECasUserDetailAuthenticationProvider.java
@Override protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { User gnDetails = userRepo.findOneByUsername(userDetails.getUsername()); if (authentication.getCredentials() == null) { logger.error("Authentication failed: no credentials provided"); throw new BadCredentialsException("Authentication failed: no credentials provided"); }//from w w w .j a va 2s. co m if (!encoder.matches(authentication.getCredentials().toString(), gnDetails.getPassword())) { logger.warn("Authentication failed: wrong password provided"); throw new BadCredentialsException("Authentication failed: wrong password provided"); } }
From source file:org.geoserver.security.iride.IrideAuthenticationProvider.java
/** * Returns the {@link UsernamePasswordAuthenticationToken} token. * * @param auth the {@link UsernamePasswordAuthenticationToken} token * @return the {@link UsernamePasswordAuthenticationToken} token * @see UsernamePasswordAuthenticationProvider#authenticate(Authentication, HttpServletRequest) */// www . ja v a2s . c om private UsernamePasswordAuthenticationToken buildAuthenticationToken(UsernamePasswordAuthenticationToken auth) { if (auth == null) { // pass request to next provider in the chain return null; } if (!auth.getAuthorities().contains(GeoServerRole.AUTHENTICATED_ROLE)) { final List<GrantedAuthority> roles = new ArrayList<>(); roles.addAll(auth.getAuthorities()); roles.add(GeoServerRole.AUTHENTICATED_ROLE); final UsernamePasswordAuthenticationToken newAuth = new UsernamePasswordAuthenticationToken( auth.getPrincipal(), auth.getCredentials(), roles); newAuth.setDetails(auth.getDetails()); return newAuth; } return auth; }
From source file:org.libreplan.web.users.services.LDAPCustomAuthenticationProvider.java
@Transactional(readOnly = true) @Override//w ww . j a v a 2 s .c o m public UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) { String clearPassword = authentication.getCredentials().toString(); if (StringUtils.isBlank(username) || StringUtils.isBlank(clearPassword)) { throw new BadCredentialsException("Username and password can not be empty"); } String encodedPassword = passwordEncoderService.encodePassword(clearPassword, username); User user = getUserFromDB(username); // If user != null then exists in LibrePlan if (null != user && user.isLibrePlanUser()) { // is a LibrePlan user, then we must authenticate against DB return authenticateInDatabase(username, user, encodedPassword); } // If it's a LDAP or null user, then we must authenticate against LDAP // Load LDAPConfiguration properties configuration = loadLDAPConfiguration(); if (configuration.getLdapAuthEnabled()) { // Sets the new context to ldapTemplate ldapTemplate.setContextSource(loadLDAPContext()); try { // Test authentication for user against LDAP if (authenticateAgainstLDAP(username, clearPassword)) { // Authentication against LDAP was ok if (null == user) { // User does not exist in LibrePlan must be imported user = createLDAPUserWithRoles(username, encodedPassword); } else { // Update password if (configuration.isLdapSavePasswordsDB()) { user.setPassword(encodedPassword); } // Update roles from LDAP setRoles(user); } saveUserOnTransaction(user); return loadUserDetails(username); } else { throw new BadCredentialsException("User is not in LDAP."); } } catch (Exception e) { // This exception captures when LDAP authentication is not possible LOG.info("LDAP not reachable. Trying to authenticate against database.", e); } } // LDAP is not enabled we must check if the LDAP user is in DB return authenticateInDatabase(username, user, encodedPassword); }
From source file:org.linagora.linshare.auth.dao.LdapAuthenticationProvider.java
@Override protected UserDetails retrieveUser(String login, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { UserDetails loadedUser;/*from w ww . ja v a 2 s. c o m*/ logger.debug("Retrieving user detail for ldap authentication with login : " + login); User foundUser = null; String domainIdentifier = null; // Getting password from context String password = (String) authentication.getCredentials(); if (password.isEmpty()) { String message = "User password is empty, authentification failed"; ldapUserDetailsProvider.logAuthError(login, domainIdentifier, message); logger.error(message); throw new BadCredentialsException(messages .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } try { // Getting domain from context if (authentication.getDetails() != null && authentication.getDetails() instanceof String) { domainIdentifier = (String) authentication.getDetails(); } foundUser = ldapUserDetailsProvider.retrieveUser(domainIdentifier, login); try { ldapUserDetailsProvider.auth(foundUser.getDomain().getUserProvider(), foundUser.getMail(), password); } catch (BadCredentialsException e1) { logger.debug("Authentication failed: password does not match stored value"); String message = "Bad credentials."; ldapUserDetailsProvider.logAuthError(foundUser, foundUser.getDomainId(), message); logger.error(message); throw new BadCredentialsException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"), foundUser); } catch (Exception e) { logger.error(e.getMessage()); throw new AuthenticationServiceException( "Could not authenticate user : " + foundUser.getDomainId() + " : " + foundUser.getMail(), e); } User user = null; try { user = ldapUserDetailsProvider.findOrCreateUser(foundUser.getDomainId(), foundUser.getMail()); } catch (BusinessException e) { logger.error(e); throw new AuthenticationServiceException( "Could not create user account : " + foundUser.getDomainId() + " : " + foundUser.getMail(), e); } List<GrantedAuthority> grantedAuthorities = RoleProvider.getRoles(user); loadedUser = new org.springframework.security.core.userdetails.User(user.getLsUuid(), "", true, true, true, true, grantedAuthorities); } catch (DataAccessException repositoryProblem) { throw new AuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem); } return loadedUser; }
From source file:org.ngrinder.security.NGrinderAuthenticationProvider.java
@SuppressWarnings("deprecation") protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) { Authentication authentication2 = SecurityContextHolder.getContext().getAuthentication(); if (authentication2 != null) { return;//from ww w. j a v a 2s. c o m } Object salt = null; if (this.saltSource != null) { salt = this.saltSource.getSalt(userDetails); } String message = messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"); if (authentication.getCredentials() == null) { LOG.debug("Authentication failed: no credentials provided"); throw new BadCredentialsException(message, userDetails); } String presentedPassword = authentication.getCredentials().toString(); SecuredUser user = ((SecuredUser) userDetails); boolean authorized = false; for (OnLoginRunnable each : getPluginManager().getEnabledModulesByClass(OnLoginRunnable.class, defaultLoginPlugin)) { if (isClassEqual(each.getClass(), defaultLoginPlugin.getClass().getName())) { if (StringUtils.isEmpty(user.getAuthProviderClass()) || isClassEqual(DefaultLoginPlugin.class, user.getUserInfoProviderClass())) { each.validateUser(user.getUsername(), presentedPassword, user.getPassword(), passwordEncoder, salt); authorized = true; break; } else { try { each.validateUser(user.getUsername(), presentedPassword, user.getPassword(), passwordEncoder, salt); authorized = true; break; } catch (Exception e) { noOp(); } } } else if (isClassEqual(each.getClass(), user.getAuthProviderClass())) { each.validateUser(user.getUsername(), presentedPassword, user.getPassword(), passwordEncoder, salt); authorized = true; break; } } if (!authorized) { throw new BadCredentialsException(message, user); } // If It's the first time to login // means.. If the user info provider is not defaultLoginPlugin.. if (user.getUserInfoProviderClass() != null && !isClassEqual(defaultLoginPlugin.getClass(), user.getUserInfoProviderClass())) { addNewUserIntoLocal(user); } }
From source file:org.opennms.protocols.radius.springsecurity.RadiusAuthenticationProvider.java
/** {@inheritDoc} */ @Override/* w ww . jav a 2 s. c o m*/ protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken token) throws AuthenticationException { if (!userDetails.getPassword().equals(token.getCredentials().toString())) { throw new BadCredentialsException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"), userDetails); } }
From source file:org.opennms.protocols.radius.springsecurity.RadiusAuthenticationProvider.java
/** {@inheritDoc} */ @Override/*from w w w. j a v a 2 s . c om*/ protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken token) throws AuthenticationException { if (!StringUtils.hasLength(username)) { logger.info("Authentication attempted with empty username"); throw new BadCredentialsException( messages.getMessage("RadiusAuthenticationProvider.emptyUsername", "Username cannot be empty")); } String password = (String) token.getCredentials(); if (!StringUtils.hasLength(password)) { logger.info("Authentication attempted with empty password"); throw new BadCredentialsException(messages .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } InetAddress serverIP = null; serverIP = InetAddressUtils.addr(server); if (serverIP == null) { logger.error("Could not resolve radius server address " + server); throw new AuthenticationServiceException(messages.getMessage( "RadiusAuthenticationProvider.unknownServer", "Could not resolve radius server address")); } AttributeFactory.loadAttributeDictionary("net.jradius.dictionary.AttributeDictionaryImpl"); AttributeList attributeList = new AttributeList(); attributeList.add(new Attr_UserName(username)); attributeList.add(new Attr_UserPassword(password)); RadiusPacket reply; try { RadiusClient radiusClient = new RadiusClient(serverIP, secret, port, port + 1, timeout); AccessRequest request = new AccessRequest(radiusClient, attributeList); logger.debug("Sending AccessRequest message to " + InetAddressUtils.str(serverIP) + ":" + port + " using " + (authTypeClass == null ? "PAP" : authTypeClass.getAuthName()) + " protocol with timeout = " + timeout + ", retries = " + retries + ", attributes:\n" + attributeList.toString()); reply = radiusClient.authenticate(request, authTypeClass, retries); } catch (RadiusException e) { logger.error("Error connecting to radius server " + server + " : " + e); throw new AuthenticationServiceException(messages.getMessage("RadiusAuthenticationProvider.radiusError", new Object[] { e }, "Error connecting to radius server: " + e)); } catch (IOException e) { logger.error("Error connecting to radius server " + server + " : " + e); throw new AuthenticationServiceException(messages.getMessage("RadiusAuthenticationProvider.radiusError", new Object[] { e }, "Error connecting to radius server: " + e)); } if (reply == null) { logger.error("Timed out connecting to radius server " + server); throw new AuthenticationServiceException(messages.getMessage( "RadiusAuthenticationProvider.radiusTimeout", "Timed out connecting to radius server")); } if (!(reply instanceof AccessAccept)) { logger.info("Received a reply other than AccessAccept from radius server " + server + " for user " + username + " :\n" + reply.toString()); throw new BadCredentialsException(messages .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } logger.debug("Received AccessAccept message from " + InetAddressUtils.str(serverIP) + ":" + port + " for user " + username + " with attributes:\n" + reply.getAttributes().toString()); String roles = null; if (!StringUtils.hasLength(rolesAttribute)) { logger.debug("rolesAttribute not set, using default roles (" + defaultRoles + ") for user " + username); roles = new String(defaultRoles); } else { Iterator<RadiusAttribute> attributes = reply.getAttributes().getAttributeList().iterator(); while (attributes.hasNext()) { RadiusAttribute attribute = attributes.next(); if (rolesAttribute.equals(attribute.getAttributeName())) { roles = new String(attribute.getValue().getBytes()); break; } } if (roles == null) { logger.info("Radius attribute " + rolesAttribute + " not found, using default roles (" + defaultRoles + ") for user " + username); roles = new String(defaultRoles); } } String[] rolesArray = roles.replaceAll("\\s*", "").split(","); Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(rolesArray.length); for (String role : rolesArray) { authorities.add(new SimpleGrantedAuthority(role)); } if (logger.isDebugEnabled()) { StringBuffer readRoles = new StringBuffer(); for (GrantedAuthority authority : authorities) { readRoles.append(authority.toString() + ", "); } if (readRoles.length() > 0) { readRoles.delete(readRoles.length() - 2, readRoles.length()); } logger.debug("Parsed roles " + readRoles + " for user " + username); } return new User(username, password, true, true, true, true, authorities); }
From source file:org.springframework.security.authentication.jaas.AbstractJaasAuthenticationProvider.java
/** * Attempts to login the user given the Authentication objects principal and * credential//from w w w.j a va 2 s. c o m * * @param auth The Authentication object to be authenticated. * * @return The authenticated Authentication object, with it's grantedAuthorities set. * * @throws AuthenticationException This implementation does not handle 'locked' or * 'disabled' accounts. This method only throws a AuthenticationServiceException, with * the message of the LoginException that will be thrown, should the * loginContext.login() method fail. */ public Authentication authenticate(Authentication auth) throws AuthenticationException { if (!(auth instanceof UsernamePasswordAuthenticationToken)) { return null; } UsernamePasswordAuthenticationToken request = (UsernamePasswordAuthenticationToken) auth; Set<GrantedAuthority> authorities; try { // Create the LoginContext object, and pass our InternallCallbackHandler LoginContext loginContext = createLoginContext(new InternalCallbackHandler(auth)); // Attempt to login the user, the LoginContext will call our // InternalCallbackHandler at this point. loginContext.login(); // Create a set to hold the authorities, and add any that have already been // applied. authorities = new HashSet<>(); // Get the subject principals and pass them to each of the AuthorityGranters Set<Principal> principals = loginContext.getSubject().getPrincipals(); for (Principal principal : principals) { for (AuthorityGranter granter : this.authorityGranters) { Set<String> roles = granter.grant(principal); // If the granter doesn't wish to grant any authorities, it should // return null. if ((roles != null) && !roles.isEmpty()) { for (String role : roles) { authorities.add(new JaasGrantedAuthority(role, principal)); } } } } // Convert the authorities set back to an array and apply it to the token. JaasAuthenticationToken result = new JaasAuthenticationToken(request.getPrincipal(), request.getCredentials(), new ArrayList<>(authorities), loginContext); // Publish the success event publishSuccessEvent(result); // we're done, return the token. return result; } catch (LoginException loginException) { AuthenticationException ase = this.loginExceptionResolver.resolveException(loginException); publishFailureEvent(request, ase); throw ase; } }
From source file:org.springframework.security.extensions.kerberos.KerberosAuthenticationProvider.java
public Authentication authenticate(Authentication authentication) throws AuthenticationException { UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication; String validatedUsername = kerberosClient.login(auth.getName(), auth.getCredentials().toString()); UserDetails userDetails = this.userDetailsService.loadUserByUsername(validatedUsername); UsernamePasswordAuthenticationToken output = new UsernamePasswordAuthenticationToken(userDetails, auth.getCredentials(), userDetails.getAuthorities()); output.setDetails(authentication.getDetails()); return output; }