List of usage examples for org.springframework.security.authentication BadCredentialsException BadCredentialsException
public BadCredentialsException(String msg)
BadCredentialsException
with the specified message. From source file:org.fao.geonet.kernel.security.ldap.LdapUserDetailsManager.java
/** * Changes the password for the current user. The username is obtained from the security * context. <p> If the old password is supplied, the update will be made by rebinding as the * user, thus modifying the password using the user's permissions. If <code>oldPassword</code> * is null, the update will be attempted using a standard read/write context supplied by the * context source. </p>/*from w w w . ja va2 s.c o m*/ * * @param oldPassword the old password * @param newPassword the new value of the password. */ public void changePassword(final String oldPassword, final String newPassword) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Assert.notNull(authentication, "No authentication object found in security context. Can't change current user's password!"); String username = authentication.getName(); logger.debug("Changing password for user '" + username); final DistinguishedName dn = usernameMapper.buildDn(username); final ModificationItem[] passwordChange = new ModificationItem[] { new ModificationItem( DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(passwordAttributeName, newPassword)) }; if (oldPassword == null) { template.modifyAttributes(dn, passwordChange); return; } template.executeReadWrite(new ContextExecutor() { public Object executeWithContext(DirContext dirCtx) throws NamingException { LdapContext ctx = (LdapContext) dirCtx; ctx.removeFromEnvironment("com.sun.jndi.ldap.connect.pool"); ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, LdapUtils.getFullDn(dn, ctx).toString()); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, oldPassword); // TODO: reconnect doesn't appear to actually change the // credentials try { ctx.reconnect(null); } catch (javax.naming.AuthenticationException e) { throw new BadCredentialsException("Authentication for password change failed."); } ctx.modifyAttributes(dn, passwordChange); return null; } }); }
From source file:org.flowable.ui.idm.security.CustomDaoAuthenticationProvider.java
protected void additionalAuthenticationChecks( org.springframework.security.core.userdetails.UserDetails userDetails, org.springframework.security.authentication.UsernamePasswordAuthenticationToken authentication) throws org.springframework.security.core.AuthenticationException { // Overriding this method to catch empty/null passwords. This happens when users are synced with LDAP sync: // they will have an external id, but no password (password is checked against ldap). ////w w w . j a v a 2 s. co m // The default DaoAuthenticationProvider will choke on an empty password (an arrayIndexOutOfBoundsException // somewhere deep in the bowels of password encryption), hence this override if (StringUtils.isEmpty(userDetails.getPassword())) { throw new BadCredentialsException(messages .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } super.additionalAuthenticationChecks(userDetails, authentication); }
From source file:org.geoserver.security.ldap.GeoserverLdapBindAuthenticator.java
/** * If userFilter is defined we extract user data using the filter and * dnPattern (if defined) to transform username for authentication. * /*from w w w . j ava2 s .com*/ * @param authentication * @return */ protected DirContextOperations authenticateUsingFilter(Authentication authentication) { DirContextOperations user = null; Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, "Can only process UsernamePasswordAuthenticationToken objects"); String username = authentication.getName(); String password = (String) authentication.getCredentials(); // format given username if required if (userFormat != null && !userFormat.equals("")) { username = MessageFormat.format(userFormat, username); } if (!StringUtils.hasLength(password)) { logger.debug("Rejecting empty password for user " + username); throw new BadCredentialsException( messages.getMessage("BindAuthenticator.emptyPassword", "Empty Password")); } DirContext ctx = null; String userDnStr = ""; try { ctx = getContextSource().getContext(username, password); // Check for password policy control PasswordPolicyControl ppolicy = PasswordPolicyControlExtractor.extractControl(ctx); logger.debug("Retrieving user object using filter..."); SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); user = SpringSecurityLdapTemplate.searchForSingleEntryInternal(ctx, searchCtls, "", userFilter, new Object[] { username }); userDnStr = user.getDn().toString(); if (ppolicy != null) { user.setAttributeValue(ppolicy.getID(), ppolicy); } } catch (NamingException e) { // This will be thrown if an invalid user name is used and the // method may // be called multiple times to try different names, so we trap the // exception // unless a subclass wishes to implement more specialized behaviour. if ((e instanceof org.springframework.ldap.AuthenticationException) || (e instanceof org.springframework.ldap.OperationNotSupportedException)) { handleBindException(userDnStr, username, e); } else { throw e; } } catch (javax.naming.NamingException e) { throw LdapUtils.convertLdapException(e); } finally { LdapUtils.closeContext(ctx); } if (user == null) { throw new BadCredentialsException( messages.getMessage("BindAuthenticator.badCredentials", "Bad credentials")); } return user; }
From source file:org.hyperic.hq.security.JdbcHQAuthenticationProvider.java
public Authentication authenticate(String username, String password) { final boolean debug = log.isDebugEnabled(); try {/*w ww . ja v a 2s .com*/ // TODO We shouldn't have to make two calls here... AuthzSubject subject = authzSubjectManager.findSubjectByAuth(username, HQConstants.ApplicationName); Principal principal = principalDao.findByUsername(username); if (password == null || principal == null) { if (debug) { log.debug("Authentication of user {" + username + "} failed because password being null."); } throw new BadCredentialsException("login.error.login"); } else if (!subject.getActive()) { if (debug) { log.debug("Authentication of user {" + username + "} failed because account is disabled."); } throw new UserDisabledException(); } else if (!passwordEncoder.isPasswordValid(principal.getPassword(), password, null)) { if (debug) { log.debug("Authentication of user {" + username + "} failed due to a login error."); } throw new BadCredentialsException("login.error.login"); } if (debug) { log.debug("Logged in as [" + username + "]"); } } catch (SubjectNotFoundException e) { if (debug) { log.debug("Authentication of user {" + username + "} failed due to a login error.", e); } throw new BadCredentialsException("login.error.login"); } // ...finally, we need to create a list grant authorities for Spring // Security... List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(); // ...TODO right now, every user is given the "ROLE HQ USER" grant // authority, once we fully integrate with // spring security this should be updated with a better approach... grantedAuthorities.add(new GrantedAuthorityImpl("ROLE_HQ_USER")); return new UsernamePasswordAuthenticationToken(username, password, grantedAuthorities); }
From source file:org.libreplan.web.users.services.LDAPCustomAuthenticationProvider.java
@Transactional(readOnly = true) @Override//from ww w. j a va 2 s .co 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.libreplan.web.users.services.LDAPCustomAuthenticationProvider.java
private UserDetails authenticateInDatabase(String username, User user, String encodedPassword) { if (null != user && null != user.getPassword() && encodedPassword.equals(user.getPassword())) { return loadUserDetails(username); } else {/*from w w w . j a v a 2 s . c om*/ throw new BadCredentialsException("Credentials are not the same as in database."); } }
From source file:org.ligoj.app.plugin.id.ldap.resource.LdapPluginResource.java
@Override public Authentication authenticate(final Authentication authentication, final String node, final boolean primary) { final UserLdapRepository repository = (UserLdapRepository) self.getConfiguration(node).getUserRepository(); // Authenticate the user if (repository.authenticate(authentication.getName(), (String) authentication.getCredentials())) { // Return a new authentication based on resolved application user return primary ? authentication : new UsernamePasswordAuthenticationToken(toApplicationUser(repository, authentication), null); }/* www . ja va2 s . co m*/ throw new BadCredentialsException(""); }
From source file:org.linagora.linshare.auth.dao.LdapAuthenticationProvider.java
@Override protected UserDetails retrieveUser(String login, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { UserDetails loadedUser;/*from w w w .j a v a 2 s .co 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.madsonic.ldap.MadsonicLdapBindAuthenticator.java
public DirContextOperations authenticate(Authentication authentication) { // LDAP authentication must be enabled on the system. if (!settingsService.isLdapEnabled()) { throw new BadCredentialsException("LDAP authentication disabled."); }// ww w .j av a2s . c om String username = authentication.getName(); LOG.info("Authentication principal: " + username); // User must be defined in Madsonic, unless auto-shadowing is enabled. User user = securityService.getUserByName(username); if (user == null && !settingsService.isLdapAutoShadowing()) { throw new BadCredentialsException("User does not exist."); } // LDAP authentication must be enabled for the given user. if (user != null && !user.isLdapAuthenticated()) { throw new BadCredentialsException("LDAP authentication disabled for user."); } try { createDelegate(); DirContextOperations contextOperations = delegateAuthenticator.authenticate(authentication); if (contextOperations != null) { LOG.info("User '" + username + "' successfully authenticated in LDAP. DN: " + contextOperations.getDn()); if (user == null) { User newUser = new User(username, "", null, true, 0L, 0L, 0L, 0, false, "#LDAP"); newUser.setStreamRole(true); newUser.setSettingsRole(true); securityService.createUser(newUser); LOG.info("Created local user '" + username + "' for DN " + contextOperations.getDn()); } } return contextOperations; } catch (RuntimeException x) { LOG.info("Failed to authenticate user '" + username + "' in LDAP.", x); throw x; } }
From source file:org.opendaylight.controller.usermanager.internal.UserManager.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (StringUtils.isBlank((String) authentication.getCredentials()) || StringUtils.isBlank((String) authentication.getPrincipal())) { throw new BadCredentialsException("Username or credentials did not match"); }//from www . ja v a2 s . co m AuthResultEnum result = authenticate((String) authentication.getPrincipal(), (String) authentication.getCredentials()); if (result.equals(AuthResultEnum.AUTHOR_PASS) || result.equals(AuthResultEnum.AUTH_ACCEPT_LOC) || result.equals(AuthResultEnum.AUTH_ACCEPT)) { AuthenticatedUser user = activeUsers.get(authentication.getPrincipal().toString()); if (user == null) { throw new AuthenticationServiceException("Authentication Failure"); } authentication = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), user.getGrantedAuthorities(getUserLevel(authentication.getName()))); return authentication; } else { throw new BadCredentialsException("Username or credentials did not match"); } }