List of usage examples for org.springframework.security.authentication BadCredentialsException BadCredentialsException
public BadCredentialsException(String msg)
BadCredentialsException
with the specified message. From source file:org.cloudfoundry.identity.uaa.authentication.manager.AuthzAuthenticationManager.java
@Override public Authentication authenticate(Authentication req) throws AuthenticationException { logger.debug("Processing authentication request for " + req.getName()); if (req.getCredentials() == null) { BadCredentialsException e = new BadCredentialsException("No password supplied"); publish(new AuthenticationFailureBadCredentialsEvent(req, e)); throw e;// w w w .j a v a2s . c o m } UaaUser user = getUaaUser(req); if (user == null) { logger.debug("No user named '" + req.getName() + "' was found for origin:" + origin); publish(new UserNotFoundEvent(req)); } else { if (!accountLoginPolicy.isAllowed(user, req)) { logger.warn("Login policy rejected authentication for " + user.getUsername() + ", " + user.getId() + ". Ignoring login request."); AuthenticationPolicyRejectionException e = new AuthenticationPolicyRejectionException( "Your account has been locked because of too many failed attempts to login."); publish(new AuthenticationFailureLockedEvent(req, e)); throw e; } boolean passwordMatches = ((CharSequence) req.getCredentials()).length() != 0 && encoder.matches((CharSequence) req.getCredentials(), user.getPassword()); if (!passwordMatches) { logger.debug("Password did not match for user " + req.getName()); publish(new UserAuthenticationFailureEvent(user, req)); } else { logger.debug( "Password successfully matched for userId[" + user.getUsername() + "]:" + user.getId()); if (!(allowUnverifiedUsers && user.isLegacyVerificationBehavior()) && !user.isVerified()) { publish(new UnverifiedUserAuthenticationEvent(user, req)); logger.debug("Account not verified: " + user.getId()); throw new AccountNotVerifiedException("Account not verified"); } checkPasswordExpired(user.getPasswordLastModified()); UaaAuthentication success = new UaaAuthentication(new UaaPrincipal(user), user.getAuthorities(), (UaaAuthenticationDetails) req.getDetails()); success.setAuthenticationMethods(Collections.singleton("pwd")); Date passwordNewerThan = getPasswordNewerThan(); if (passwordNewerThan != null) { if (user.getPasswordLastModified() == null || (passwordNewerThan.getTime() > user.getPasswordLastModified().getTime())) { logger.info("Password change required for user: " + user.getEmail()); throw new PasswordChangeRequiredException(success, "User password needs to be changed"); } } if (user.isPasswordChangeRequired()) { logger.info("Password change required for user: " + user.getEmail()); throw new PasswordChangeRequiredException(success, "User password needs to be changed"); } publish(new UserAuthenticationSuccessEvent(user, success)); return success; } } BadCredentialsException e = new BadCredentialsException("Bad credentials"); publish(new AuthenticationFailureBadCredentialsEvent(req, e)); throw e; }
From source file:org.cloudfoundry.identity.uaa.authentication.manager.ExternalLoginAuthenticationManager.java
@Override public Authentication authenticate(Authentication request) throws AuthenticationException { logger.debug("Starting external authentication for:" + request); ExternalAuthenticationDetails authenticationData = getExternalAuthenticationDetails(request); UaaUser userFromRequest = getUser(request, authenticationData); if (userFromRequest == null) { return null; }//from www . j a va 2s . c o m UaaUser userFromDb; try { logger.debug(String.format("Searching for user by (username:%s , origin:%s)", userFromRequest.getUsername(), getOrigin())); userFromDb = userDatabase.retrieveUserByName(userFromRequest.getUsername(), getOrigin()); } catch (UsernameNotFoundException e) { logger.debug(String.format("Searching for user by (email:%s , origin:%s)", userFromRequest.getEmail(), getOrigin())); userFromDb = userDatabase.retrieveUserByEmail(userFromRequest.getEmail(), getOrigin()); } // Register new users automatically if (userFromDb == null) { if (!isAddNewShadowUser()) { throw new AccountNotPreCreatedException( "The user account must be pre-created. Please contact your system administrator."); } publish(new NewUserAuthenticatedEvent(userFromRequest)); try { userFromDb = userDatabase.retrieveUserByName(userFromRequest.getUsername(), getOrigin()); } catch (UsernameNotFoundException ex) { throw new BadCredentialsException("Unable to register user in internal UAA store."); } } //user is authenticated and exists in UAA UaaUser user = userAuthenticated(request, userFromRequest, userFromDb); UaaAuthenticationDetails uaaAuthenticationDetails; if (request.getDetails() instanceof UaaAuthenticationDetails) { uaaAuthenticationDetails = (UaaAuthenticationDetails) request.getDetails(); } else { uaaAuthenticationDetails = UaaAuthenticationDetails.UNKNOWN; } UaaAuthentication success = new UaaAuthentication(new UaaPrincipal(user), user.getAuthorities(), uaaAuthenticationDetails); populateAuthenticationAttributes(success, request, authenticationData); publish(new UserAuthenticationSuccessEvent(user, success)); return success; }
From source file:org.cloudfoundry.identity.uaa.authentication.manager.ExternalLoginAuthenticationManager.java
protected String generateEmailIfNull(String name) { String email;//from w ww. j a va 2s .co m if (name != null) { if (name.contains("@")) { if (name.split("@").length == 2 && !name.startsWith("@") && !name.endsWith("@")) { email = name; } else { email = name.replaceAll("@", "") + "@user.from." + getOrigin() + ".cf"; } } else { email = name + "@user.from." + getOrigin() + ".cf"; } } else { throw new BadCredentialsException("Cannot determine username from credentials supplied"); } return email; }
From source file:org.cloudfoundry.identity.uaa.authentication.manager.LoginAuthenticationManager.java
@Override public Authentication authenticate(Authentication request) throws AuthenticationException { if (!(request instanceof AuthzAuthenticationRequest)) { logger.debug("Cannot process request of type: " + request.getClass().getName()); return null; }/*from www .ja v a2 s . c om*/ AuthzAuthenticationRequest req = (AuthzAuthenticationRequest) request; Map<String, String> info = req.getInfo(); logger.debug("Processing authentication request for " + req.getName()); SecurityContext context = SecurityContextHolder.getContext(); if (context.getAuthentication() instanceof OAuth2Authentication) { OAuth2Authentication authentication = (OAuth2Authentication) context.getAuthentication(); if (authentication.isClientOnly()) { UaaUser user = getUser(req, info); UaaAuthenticationDetails authdetails = (UaaAuthenticationDetails) req.getDetails(); boolean addNewAccounts = authdetails != null && authdetails.isAddNew(); try { if (NotANumber.equals(user.getId())) { user = userDatabase.retrieveUserByName(user.getUsername(), user.getOrigin()); } else { //we should never add new accounts if we specify user_id addNewAccounts = false; user = userDatabase.retrieveUserById(user.getId()); } } catch (UsernameNotFoundException e) { // Not necessarily fatal if (addNewAccounts) { // Register new users automatically publish(new NewUserAuthenticatedEvent(user)); try { user = userDatabase.retrieveUserByName(user.getUsername(), user.getOrigin()); } catch (UsernameNotFoundException ex) { throw new BadCredentialsException("Bad credentials"); } } else { //if add_new=false then this is a bad user ID throw new BadCredentialsException("Bad Credentials"); } } Authentication success = new UaaAuthentication(new UaaPrincipal(user), user.getAuthorities(), authdetails); publish(new UserAuthenticationSuccessEvent(user, success)); return success; } } logger.debug("Did not locate login credentials"); return null; }
From source file:org.cloudfoundry.identity.uaa.authentication.manager.LoginAuthenticationManager.java
protected UaaUser getUser(AuthzAuthenticationRequest req, Map<String, String> info) { String name = req.getName();//from w ww . j a va 2s . c o m String email = info.get("email"); String userId = info.get("user_id") != null ? info.get("user_id") : NotANumber; if (info.get(OriginKeys.ORIGIN) != null && info.get(OriginKeys.ORIGIN).equals(OriginKeys.UAA)) { throw new BadCredentialsException("uaa origin not allowed for external login server"); } String origin = info.get(OriginKeys.ORIGIN) != null ? info.get(OriginKeys.ORIGIN) : OriginKeys.LOGIN_SERVER; if (name == null && email != null) { name = email; } if (name == null && NotANumber.equals(userId)) { throw new BadCredentialsException("Cannot determine username from credentials supplied"); } else if (name == null) { //we have user_id, name is irrelevant name = "unknown"; } if (email == null) { if (name.contains("@")) { if (name.split("@").length == 2 && !name.startsWith("@") && !name.endsWith("@")) { email = name; } else { email = name.replaceAll("@", "") + "@unknown.org"; } } else { email = name + "@unknown.org"; } } String givenName = info.get("given_name"); if (givenName == null) { givenName = email.split("@")[0]; } String familyName = info.get("family_name"); if (familyName == null) { familyName = (email.split("@").length > 1 ? email.split("@")[1] : email); } return new UaaUser(userId, name, "" /*zero length password for login server */, email, UaaAuthority.USER_AUTHORITIES, givenName, familyName, new Date(), new Date(), origin, name, false, IdentityZoneHolder.get().getId(), null, null); }
From source file:org.cloudfoundry.identity.uaa.authentication.manager.RestAuthenticationManager.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = authentication.getName(); String password = (String) authentication.getCredentials(); HttpHeaders headers = getHeaders();//from w ww. ja va2s . c o m @SuppressWarnings("rawtypes") ResponseEntity<Map> response = restTemplate.exchange(remoteUrl, HttpMethod.POST, new HttpEntity<Object>(getParameters(username, password), headers), Map.class); if (response.getStatusCode() == HttpStatus.OK || response.getStatusCode() == HttpStatus.CREATED) { if (evaluateResponse(authentication, response)) { logger.info("Successful authentication request for " + authentication.getName()); //TODO - we can return a UAA principal containing the correct origin here. return new UsernamePasswordAuthenticationToken(username, nullPassword ? null : "", UaaAuthority.USER_AUTHORITIES); } } else if (response.getStatusCode() == HttpStatus.UNAUTHORIZED) { logger.info("Failed authentication request"); throw new BadCredentialsException("Authentication failed"); } else if (response.getStatusCode() == HttpStatus.INTERNAL_SERVER_ERROR) { logger.info("Internal error from UAA. Please Check the UAA logs."); } else { logger.error("Unexpected status code " + response.getStatusCode() + " from the UAA." + " Is a compatible version running?"); } throw new RuntimeException("Could not authenticate with remote server"); }
From source file:org.cloudfoundry.identity.uaa.ldap.PasswordComparisonAuthenticator.java
public DirContextOperations searchAuthenticate(DirContextOperations user, byte[] passwordBytes, SpringSecurityLdapTemplate ldapTemplate) { if (logger.isDebugEnabled()) { logger.debug("Performing LDAP compare of password attribute '" + passwordAttributeName + "' for user '" + user.getDn() + "'"); }// ww w . ja va2 s.c o m if (!ldapTemplate.compare(user.getDn().toString(), passwordAttributeName, passwordBytes)) { throw new BadCredentialsException( messages.getMessage("PasswordComparisonAuthenticator.badCredentials", "Bad credentials")); } return user; }
From source file:org.cloudfoundry.identity.uaa.login.LoginInfoEndpoint.java
@RequestMapping(value = "/autologin", method = RequestMethod.POST) @ResponseBody//from w w w . j a va 2s.co m public AutologinResponse generateAutologinCode(@RequestBody AutologinRequest request, @RequestHeader(value = "Authorization", required = false) String auth) throws Exception { if (auth == null || (!auth.startsWith("Basic"))) { throw new BadCredentialsException("No basic authorization client information in request"); } String username = request.getUsername(); if (username == null) { throw new BadCredentialsException("No username in request"); } Authentication userAuthentication = null; if (authenticationManager != null) { String password = request.getPassword(); if (!hasText(password)) { throw new BadCredentialsException("No password in request"); } userAuthentication = authenticationManager .authenticate(new AuthzAuthenticationRequest(username, password, null)); } String base64Credentials = auth.substring("Basic".length()).trim(); String credentials = new String(new Base64().decode(base64Credentials.getBytes()), UTF_8.name()); // credentials = username:password final String[] values = credentials.split(":", 2); if (values == null || values.length == 0) { throw new BadCredentialsException("Invalid authorization header."); } String clientId = values[0]; Map<String, String> codeData = new HashMap<>(); codeData.put("client_id", clientId); codeData.put("username", username); if (userAuthentication != null && userAuthentication.getPrincipal() instanceof UaaPrincipal) { UaaPrincipal p = (UaaPrincipal) userAuthentication.getPrincipal(); if (p != null) { codeData.put("user_id", p.getId()); codeData.put(OriginKeys.ORIGIN, p.getOrigin()); } } ExpiringCode expiringCode = expiringCodeStore.generateCode(JsonUtils.writeValueAsString(codeData), new Timestamp(System.currentTimeMillis() + 5 * 60 * 1000), ExpiringCodeType.AUTOLOGIN.name(), IdentityZoneHolder.get().getId()); return new AutologinResponse(expiringCode.getCode()); }
From source file:org.cloudfoundry.identity.uaa.login.saml.LoginSamlAuthenticationProvider.java
protected UaaUser createIfMissing(UaaPrincipal samlPrincipal, boolean addNew, Collection<? extends GrantedAuthority> authorities, MultiValueMap<String, String> userAttributes) { UaaUser user = null;/*from w w w.j a v a 2 s .c om*/ String invitedUserId = null; boolean is_invitation_acceptance = isAcceptedInvitationAuthentication(); if (is_invitation_acceptance) { invitedUserId = (String) RequestContextHolder.currentRequestAttributes().getAttribute("user_id", RequestAttributes.SCOPE_SESSION); user = userDatabase.retrieveUserById(invitedUserId); if (userAttributes.getFirst(EMAIL_ATTRIBUTE_NAME) != null) { if (!userAttributes.getFirst(EMAIL_ATTRIBUTE_NAME).equalsIgnoreCase(user.getEmail())) { throw new BadCredentialsException( "SAML User email mismatch. Authenticated email doesn't match invited email."); } } else { userAttributes = new LinkedMultiValueMap<>(userAttributes); userAttributes.add(EMAIL_ATTRIBUTE_NAME, user.getEmail()); } addNew = false; if (user.getUsername().equals(user.getEmail()) && !user.getUsername().equals(samlPrincipal.getName())) { user.setVerified(true); user = user.modifyUsername(samlPrincipal.getName()); } publish(new InvitedUserAuthenticatedEvent(user)); user = userDatabase.retrieveUserById(invitedUserId); } boolean userModified = false; UaaUser userWithSamlAttributes = getUser(samlPrincipal, userAttributes); try { if (user == null) { user = userDatabase.retrieveUserByName(samlPrincipal.getName(), samlPrincipal.getOrigin()); } } catch (UsernameNotFoundException e) { if (!addNew) { throw new LoginSAMLException("SAML user does not exist. " + "You can correct this by creating a shadow user for the SAML user.", e); } // Register new users automatically publish(new NewUserAuthenticatedEvent(userWithSamlAttributes)); try { user = userDatabase.retrieveUserByName(samlPrincipal.getName(), samlPrincipal.getOrigin()); } catch (UsernameNotFoundException ex) { throw new BadCredentialsException( "Unable to establish shadow user for SAML user:" + samlPrincipal.getName()); } } if (haveUserAttributesChanged(user, userWithSamlAttributes)) { userModified = true; user = user.modifyAttributes(userWithSamlAttributes.getEmail(), userWithSamlAttributes.getGivenName(), userWithSamlAttributes.getFamilyName(), userWithSamlAttributes.getPhoneNumber()); } publish(new ExternalGroupAuthorizationEvent(user, userModified, authorities, true)); user = userDatabase.retrieveUserById(user.getId()); UaaPrincipal result = new UaaPrincipal(user); Authentication success = new UaaAuthentication(result, user.getAuthorities(), null); publish(new UserAuthenticationSuccessEvent(user, success)); return user; }
From source file:org.cloudfoundry.identity.uaa.login.saml.LoginSamlAuthenticationProvider.java
protected UaaUser getUser(UaaPrincipal principal, MultiValueMap<String, String> userAttributes) { String name = principal.getName(); String email = userAttributes.getFirst(EMAIL_ATTRIBUTE_NAME); String givenName = userAttributes.getFirst(GIVEN_NAME_ATTRIBUTE_NAME); String familyName = userAttributes.getFirst(FAMILY_NAME_ATTRIBUTE_NAME); String phoneNumber = userAttributes.getFirst(PHONE_NUMBER_ATTRIBUTE_NAME); String userId = Origin.NotANumber; String origin = principal.getOrigin() != null ? principal.getOrigin() : Origin.LOGIN_SERVER; String zoneId = principal.getZoneId(); if (name == null && email != null) { name = email;/* ww w . j ava 2s.com*/ } if (name == null && Origin.NotANumber.equals(userId)) { throw new BadCredentialsException("Cannot determine username from credentials supplied"); } else if (name == null) { //we have user_id, name is irrelevant name = "unknown"; } if (email == null) { if (name.contains("@")) { if (name.split("@").length == 2 && !name.startsWith("@") && !name.endsWith("@")) { email = name; } else { email = name.replaceAll("@", "") + "@unknown.org"; } } else { email = name + "@unknown.org"; } } if (givenName == null) { givenName = email.split("@")[0]; } if (familyName == null) { familyName = email.split("@")[1]; } return new UaaUser(new UaaUserPrototype().withEmail(email).withGivenName(givenName) .withFamilyName(familyName).withPhoneNumber(phoneNumber).withModified(new Date()).withId(userId) .withUsername(name).withPassword("").withAuthorities(Collections.EMPTY_LIST).withCreated(new Date()) .withOrigin(origin).withExternalId(name).withVerified(true).withZoneId(zoneId).withSalt(null) .withPasswordLastModified(null)); }