List of usage examples for org.springframework.security.authentication BadCredentialsException BadCredentialsException
public BadCredentialsException(String msg)
BadCredentialsException
with the specified message. From source file:org.opennms.protocols.radius.springsecurity.RadiusAuthenticationProvider.java
/** {@inheritDoc} */ @Override//from w w w . ja va2s .c o m 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.dao.AbstractUserDetailsAuthenticationProvider.java
public Authentication authenticate(Authentication authentication) throws AuthenticationException { Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, () -> messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports", "Only UsernamePasswordAuthenticationToken is supported")); // Determine username String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" : authentication.getName(); boolean cacheWasUsed = true; UserDetails user = this.userCache.getUserFromCache(username); if (user == null) { cacheWasUsed = false;//from w w w. j ava 2 s .c om try { user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication); } catch (UsernameNotFoundException notFound) { logger.debug("User '" + username + "' not found"); if (hideUserNotFoundExceptions) { throw new BadCredentialsException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } else { throw notFound; } } Assert.notNull(user, "retrieveUser returned null - a violation of the interface contract"); } try { preAuthenticationChecks.check(user); additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken) authentication); } catch (AuthenticationException exception) { if (cacheWasUsed) { // There was a problem, so try again after checking // we're using latest data (i.e. not from the cache) cacheWasUsed = false; user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication); preAuthenticationChecks.check(user); additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken) authentication); } else { throw exception; } } postAuthenticationChecks.check(user); if (!cacheWasUsed) { this.userCache.putUserInCache(user); } Object principalToReturn = user; if (forcePrincipalAsString) { principalToReturn = user.getUsername(); } return createSuccessAuthentication(principalToReturn, authentication, user); }
From source file:org.springframework.security.authentication.jaas.DefaultJaasAuthenticationProviderTests.java
License:asdf
@Test public void publishNullPublisher() { provider.setApplicationEventPublisher(null); AuthenticationException ae = new BadCredentialsException("Failed to login"); provider.publishFailureEvent(token, ae); provider.publishSuccessEvent(token); }
From source file:org.springframework.security.ldap.authentication.AbstractLdapAuthenticationProvider.java
public Authentication authenticate(Authentication authentication) throws AuthenticationException { Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, messages.getMessage("LdapAuthenticationProvider.onlySupports", "Only UsernamePasswordAuthenticationToken is supported")); final UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken) authentication; String username = userToken.getName(); String password = (String) authentication.getCredentials(); if (logger.isDebugEnabled()) { logger.debug("Processing authentication request for user: " + username); }//from w w w . j a v a 2 s . c om if (!StringUtils.hasLength(username)) { throw new BadCredentialsException( messages.getMessage("LdapAuthenticationProvider.emptyUsername", "Empty Username")); } if (!StringUtils.hasLength(password)) { throw new BadCredentialsException( messages.getMessage("AbstractLdapAuthenticationProvider.emptyPassword", "Empty Password")); } Assert.notNull(password, "Null password was supplied in authentication token"); DirContextOperations userData = doAuthentication(userToken); UserDetails user = userDetailsContextMapper.mapUserFromContext(userData, authentication.getName(), loadUserAuthorities(userData, authentication.getName(), (String) authentication.getCredentials())); return createSuccessfulAuthentication(userToken, user); }
From source file:org.springframework.security.ldap.authentication.BindAuthenticator.java
public DirContextOperations authenticate(Authentication authentication) { DirContextOperations user = null;/* ww w .j a va 2 s .co m*/ Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, "Can only process UsernamePasswordAuthenticationToken objects"); String username = authentication.getName(); String password = (String) authentication.getCredentials(); if (!StringUtils.hasLength(password)) { logger.debug("Rejecting empty password for user " + username); throw new BadCredentialsException( messages.getMessage("BindAuthenticator.emptyPassword", "Empty Password")); } // If DN patterns are configured, try authenticating with them directly for (String dn : getUserDns(username)) { user = bindWithDn(dn, username, password); if (user != null) { break; } } // Otherwise use the configured search object to find the user and authenticate // with the returned DN. if (user == null && getUserSearch() != null) { DirContextOperations userFromSearch = getUserSearch().searchForUser(username); user = bindWithDn(userFromSearch.getDn().toString(), username, password, userFromSearch.getAttributes()); } if (user == null) { throw new BadCredentialsException( messages.getMessage("BindAuthenticator.badCredentials", "Bad credentials")); } return user; }
From source file:org.springframework.security.ldap.authentication.LdapAuthenticationProvider.java
public Authentication authenticate(Authentication authentication) throws AuthenticationException { Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports", "Only UsernamePasswordAuthenticationToken is supported")); final UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken) authentication; String username = userToken.getName(); String password = (String) authentication.getCredentials(); if (logger.isDebugEnabled()) { logger.debug("Processing authentication request for user: " + username); }//from w w w . ja va 2 s .c o m if (!StringUtils.hasLength(username)) { throw new BadCredentialsException( messages.getMessage("LdapAuthenticationProvider.emptyUsername", "Empty Username")); } Assert.notNull(password, "Null password was supplied in authentication token"); try { DirContextOperations userData = getAuthenticator().authenticate(authentication); Collection<GrantedAuthority> extraAuthorities = loadUserAuthorities(userData, username, password); UserDetails user = userDetailsContextMapper.mapUserFromContext(userData, username, extraAuthorities); return createSuccessfulAuthentication(userToken, user); } catch (PasswordPolicyException ppe) { // The only reason a ppolicy exception can occur during a bind is that the account is locked. throw new LockedException( messages.getMessage(ppe.getStatus().getErrorCode(), ppe.getStatus().getDefaultMessage())); } catch (UsernameNotFoundException notFound) { if (hideUserNotFoundExceptions) { throw new BadCredentialsException( messages.getMessage("LdapAuthenticationProvider.badCredentials", "Bad credentials")); } else { throw notFound; } } catch (NamingException ldapAccessFailure) { throw new AuthenticationServiceException(ldapAccessFailure.getMessage(), ldapAccessFailure); } }
From source file:org.springframework.security.ldap.authentication.PasswordComparisonAuthenticator.java
public DirContextOperations authenticate(final Authentication authentication) { Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, "Can only process UsernamePasswordAuthenticationToken objects"); // locate the user and check the password DirContextOperations user = null;//ww w . j a va 2 s.c om String username = authentication.getName(); String password = (String) authentication.getCredentials(); SpringSecurityLdapTemplate ldapTemplate = new SpringSecurityLdapTemplate(getContextSource()); for (String userDn : getUserDns(username)) { try { user = ldapTemplate.retrieveEntry(userDn, getUserAttributes()); } catch (NameNotFoundException ignore) { } if (user != null) { break; } } if (user == null && getUserSearch() != null) { user = getUserSearch().searchForUser(username); } if (user == null) { throw new UsernameNotFoundException("User not found: " + username); } if (logger.isDebugEnabled()) { logger.debug("Performing LDAP compare of password attribute '" + passwordAttributeName + "' for user '" + user.getDn() + "'"); } if (usePasswordAttrCompare && isPasswordAttrCompare(user, password)) { return user; } else if (isLdapPasswordCompare(user, ldapTemplate, password)) { return user; } throw new BadCredentialsException( messages.getMessage("PasswordComparisonAuthenticator.badCredentials", "Bad credentials")); }
From source file:org.springframework.security.ldap.userdetails.LdapUserDetailsManager.java
private void changePasswordUsingAttributeModification(DistinguishedName userDn, String oldPassword, String newPassword) {//w w w .ja v a2s.com final ModificationItem[] passwordChange = new ModificationItem[] { new ModificationItem( DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(passwordAttributeName, newPassword)) }; if (oldPassword == null) { template.modifyAttributes(userDn, passwordChange); return; } template.executeReadWrite(dirCtx -> { LdapContext ctx = (LdapContext) dirCtx; ctx.removeFromEnvironment("com.sun.jndi.ldap.connect.pool"); ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, LdapUtils.getFullDn(userDn, 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(userDn, passwordChange); return null; }); }
From source file:org.springframework.security.ldap.userdetails.LdapUserDetailsManager.java
private void changePasswordUsingExtensionOperation(DistinguishedName userDn, String oldPassword, String newPassword) {//from www .j a v a2 s . c o m template.executeReadWrite(dirCtx -> { LdapContext ctx = (LdapContext) dirCtx; String userIdentity = LdapUtils.getFullDn(userDn, ctx).encode(); PasswordModifyRequest request = new PasswordModifyRequest(userIdentity, oldPassword, newPassword); try { return ctx.extendedOperation(request); } catch (javax.naming.AuthenticationException e) { throw new BadCredentialsException("Authentication for password change failed."); } }); }
From source file:org.springframework.security.oauth2.provider.endpoint.TokenEndpointAuthenticationFilter.java
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { final boolean debug = logger.isDebugEnabled(); final HttpServletRequest request = (HttpServletRequest) req; final HttpServletResponse response = (HttpServletResponse) res; try {//from w w w . ja v a 2s. c o m Authentication credentials = extractCredentials(request); if (credentials != null) { if (debug) { logger.debug("Authentication credentials found for '" + credentials.getName() + "'"); } Authentication authResult = authenticationManager.authenticate(credentials); if (debug) { logger.debug("Authentication success: " + authResult.getName()); } Authentication clientAuth = SecurityContextHolder.getContext().getAuthentication(); if (clientAuth == null) { throw new BadCredentialsException( "No client authentication found. Remember to put a filter upstream of the TokenEndpointAuthenticationFilter."); } DefaultAuthorizationRequest authorizationRequest = new DefaultAuthorizationRequest( getSingleValueMap(request), null, clientAuth.getName(), getScope(request)); if (clientAuth.isAuthenticated()) { // Ensure the OAuth2Authentication is authenticated authorizationRequest.setApproved(true); } SecurityContextHolder.getContext() .setAuthentication(new OAuth2Authentication(authorizationRequest, authResult)); onSuccessfulAuthentication(request, response, authResult); } } catch (AuthenticationException failed) { SecurityContextHolder.clearContext(); if (debug) { logger.debug("Authentication request for failed: " + failed); } onUnsuccessfulAuthentication(request, response, failed); authenticationEntryPoint.commence(request, response, failed); return; } chain.doFilter(request, response); }