List of usage examples for org.springframework.security.core Authentication getCredentials
Object getCredentials();
From source file:org.apache.syncope.core.spring.security.UsernamePasswordAuthenticationProvider.java
@Override public Authentication authenticate(final Authentication authentication) { String domainKey = SyncopeAuthenticationDetails.class.cast(authentication.getDetails()).getDomain(); final String[] username = new String[1]; Boolean authenticated;/*from w w w .j a v a 2 s.co m*/ if (anonymousUser.equals(authentication.getName())) { username[0] = anonymousUser; credentialChecker.checkIsDefaultAnonymousKeyInUse(); authenticated = authentication.getCredentials().toString().equals(anonymousKey); } else if (adminUser.equals(authentication.getName())) { username[0] = adminUser; if (SyncopeConstants.MASTER_DOMAIN.equals(domainKey)) { credentialChecker.checkIsDefaultAdminPasswordInUse(); authenticated = ENCRYPTOR.verify(authentication.getCredentials().toString(), CipherAlgorithm.valueOf(adminPasswordAlgorithm), adminPassword); } else { final String domainToFind = domainKey; authenticated = AuthContextUtils.execWithAuthContext(SyncopeConstants.MASTER_DOMAIN, () -> { Domain domain = dataAccessor.findDomain(domainToFind); return ENCRYPTOR.verify(authentication.getCredentials().toString(), domain.getAdminCipherAlgorithm(), domain.getAdminPwd()); }); } } else { final Pair<User, Boolean> authResult = AuthContextUtils.execWithAuthContext(domainKey, () -> dataAccessor.authenticate(authentication)); authenticated = authResult.getValue(); if (authResult.getLeft() != null && authResult.getRight() != null) { username[0] = authResult.getLeft().getUsername(); if (!authResult.getRight()) { AuthContextUtils.execWithAuthContext(domainKey, () -> { provisioningManager.internalSuspend(authResult.getLeft().getKey()); return null; }); } } } if (username[0] == null) { username[0] = authentication.getPrincipal().toString(); } final boolean isAuthenticated = authenticated != null && authenticated; UsernamePasswordAuthenticationToken token; if (isAuthenticated) { token = AuthContextUtils.execWithAuthContext(domainKey, () -> { UsernamePasswordAuthenticationToken token1 = new UsernamePasswordAuthenticationToken(username[0], null, dataAccessor.getAuthorities(username[0])); token1.setDetails(authentication.getDetails()); dataAccessor.audit(AuditElements.EventCategoryType.LOGIC, AuditElements.AUTHENTICATION_CATEGORY, null, AuditElements.LOGIN_EVENT, Result.SUCCESS, null, isAuthenticated, authentication, "Successfully authenticated, with entitlements: " + token1.getAuthorities()); return token1; }); LOG.debug("User {} successfully authenticated, with entitlements {}", username[0], token.getAuthorities()); } else { AuthContextUtils.execWithAuthContext(domainKey, () -> { dataAccessor.audit(AuditElements.EventCategoryType.LOGIC, AuditElements.AUTHENTICATION_CATEGORY, null, AuditElements.LOGIN_EVENT, Result.FAILURE, null, isAuthenticated, authentication, "User " + username[0] + " not authenticated"); return null; }); LOG.debug("User {} not authenticated", username[0]); throw new BadCredentialsException("User " + username[0] + " not authenticated"); } return token; }
From source file:org.apereo.portal.soffit.security.SoffitApiAuthenticationManager.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { logger.debug("Authenticating the following Authentication object: {}", authentication); if (!SoffitApiUserDetails.class.isInstance(authentication.getPrincipal())) { throw new BadCredentialsException("Unrecognized principal type"); }//from w w w . jav a 2s .c o m final SoffitApiUserDetails saud = (SoffitApiUserDetails) authentication.getPrincipal(); if (StringUtils.isBlank(saud.getUsername())) { throw new BadCredentialsException("Missing username"); } return new UsernamePasswordAuthenticationToken(saud.getUsername(), authentication.getCredentials(), saud.getAuthorities()); }
From source file:org.artifactory.security.ldap.ArtifactoryLdapAuthenticationProvider.java
@Override public Authentication authenticate(Authentication authentication) { String userName = authentication.getName(); // If it's an anonymous user, don't bother searching for the user. if (UserInfo.ANONYMOUS.equals(userName)) { return null; }/*from w ww .j av a2s .c om*/ log.debug("Trying to authenticate user '{}' via ldap.", userName); LdapSetting usedLdapSetting = null; DirContextOperations user = null; AddonsManager addonsManager = InternalContextHelper.get().beanForType(AddonsManager.class); LdapGroupAddon ldapGroupAddon = addonsManager.addonByType(LdapGroupAddon.class); try { RuntimeException authenticationException = null; for (Map.Entry<String, BindAuthenticator> entry : authenticator.getAuthenticators().entrySet()) { LdapSetting currentLdapSetting = centralConfig.getDescriptor().getSecurity() .getLdapSettings(entry.getKey()); BindAuthenticator bindAuthenticator = entry.getValue(); try { user = bindAuthenticator.authenticate(authentication); if (user != null) { usedLdapSetting = currentLdapSetting; break; } } catch (AuthenticationException e) { authenticationException = e; checkIfBindAndSearchActive(currentLdapSetting, userName); } catch (org.springframework.security.core.AuthenticationException e) { authenticationException = e; checkIfBindAndSearchActive(currentLdapSetting, userName); } catch (RuntimeException e) { authenticationException = e; } } if (user == null) { if (authenticationException != null) { UserInfo userInfo = userGroupService.findUser(userName); if (userInfo != null) { log.debug("user {} failed to perform ldap authentication (not bad credential)", userInfo.getUsername()); removeUserLdapRelatedGroups(userInfo); } throw authenticationException; } throw new AuthenticationServiceException(ArtifactoryLdapAuthenticator.LDAP_SERVICE_MISCONFIGURED); } // user authenticated via ldap log.debug("'{}' authenticated successfully by ldap server.", userName); //Collect internal groups, and if using external groups add them to the user info MutableUserInfo userInfo = InfoFactoryHolder.get().copyUser( userGroupService.findOrCreateExternalAuthUser(userName, !usedLdapSetting.isAutoCreateUser())); userInfo.setRealm(LdapService.REALM); String emailAttribute = usedLdapSetting.getEmailAttribute(); if (StringUtils.isNotBlank(emailAttribute)) { String email = user.getStringAttribute(emailAttribute); if (StringUtils.isNotBlank(email)) { log.debug("User '{}' has email address '{}'", userName, email); userInfo.setEmail(email); } } log.debug("Loading LDAP groups"); ldapGroupAddon.populateGroups(user, userInfo); log.debug("Finished Loading LDAP groups"); SimpleUser simpleUser = new SimpleUser(userInfo); // update user with latest attribute userGroupService.updateUser(userInfo, false); // create new authentication response containing the user and it's authorities return new LdapRealmAwareAuthentication(simpleUser, authentication.getCredentials(), simpleUser.getAuthorities()); } catch (AuthenticationException e) { String message = String.format("Failed to authenticate user '%s' via LDAP: %s", userName, e.getMessage()); log.debug(message); throw new AuthenticationServiceException(message, e); } catch (CommunicationException ce) { String message = String.format("Failed to authenticate user '%s' via LDAP: communication error", userName); log.warn(message); log.debug(message, ce); throw new AuthenticationServiceException(message, ce); } catch (org.springframework.security.core.AuthenticationException e) { String message = String.format("Failed to authenticate user '%s' via LDAP: %s", userName, e.getMessage()); log.debug(message); throw e; } catch (NamingException e) { String message = String.format("Failed to locate directory entry for authenticated user: %s", e.getMostSpecificCause().getMessage()); log.debug(message); throw new AuthenticationServiceException(message, e); } catch (InvalidNameException e) { String message = String.format("Failed to persist user '%s': %s", userName, e.getMessage()); log.warn(message); log.debug("Cause: {}", e); throw new InternalAuthenticationServiceException(message, e); } catch (Exception e) { String message = "Unexpected exception in LDAP authentication:"; log.error(message, e); throw new AuthenticationServiceException(message, e); } finally { LdapUtils.closeContext(user); } }
From source file:org.artifactory.security.SecurityServiceImpl.java
@Override public String currentUserEncryptedPassword(boolean escape) { Authentication authentication = AuthenticationHelper.getAuthentication(); if ((authentication != null) && authentication.isAuthenticated()) { String authUsername = ((UserDetails) authentication.getPrincipal()).getUsername(); String password = (String) authentication.getCredentials(); if (StringUtils.isNotBlank(password)) { UserInfo user = userGroupStoreService.findUser(authUsername); if (user == null) { log.warn("Can't return the encrypted password of the unfound user '{}'", authUsername); } else { String encrypted = createEncryptedPasswordIfNeeded(user, password); if (!encrypted.equals(password)) { if (escape) { return CryptoHelper.needsEscaping(encrypted); } else { return encrypted; }//from w ww . j av a 2 s .c o m } } } } return null; }
From source file:org.artifactory.security.SecurityServiceImpl.java
@Override public boolean userPasswordMatches(String passwordToCheck) { Authentication authentication = AuthenticationHelper.getAuthentication(); return authentication != null && passwordToCheck.equals(authentication.getCredentials()); }
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;/*from w w w. ja va 2s .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.ChainedAuthenticationManager.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (authentication == null) { return authentication; }/*from w w w. ja v a2s . c o m*/ UsernamePasswordAuthenticationToken output = null; if (authentication instanceof UsernamePasswordAuthenticationToken) { output = (UsernamePasswordAuthenticationToken) authentication; } else { output = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), authentication.getAuthorities()); output.setDetails(authentication.getDetails()); } boolean authenticated = false; Authentication auth = null; AuthenticationException lastException = null; boolean lastResult = false; boolean shallContinue = true; if (delegates == null || delegates.length == 0) { throw new ProviderNotFoundException("No available authentication providers."); } for (int i = 0; shallContinue && i < delegates.length; i++) { boolean shallAuthenticate = (i == 0) || (lastResult && IF_PREVIOUS_TRUE.equals(delegates[i].getRequired())) || ((!lastResult) && IF_PREVIOUS_FALSE.equals(delegates[i].getRequired())); if (shallAuthenticate) { if (logger.isDebugEnabled()) { logger.debug("Attempting chained authentication of " + output + " with manager:" + delegates[i].getAuthenticationManager() + " required:" + delegates[i].getRequired()); } Authentication thisAuth = null; try { thisAuth = delegates[i].getAuthenticationManager().authenticate(auth != null ? auth : output); } catch (AuthenticationException x) { if (logger.isDebugEnabled()) { logger.debug("Chained authentication exception:" + x.getMessage() + " at:" + (x.getStackTrace().length > 0 ? x.getStackTrace()[0] : "(no stack trace)")); } lastException = x; if (delegates[i].getStopIf() != null) { for (Class<? extends AuthenticationException> exceptionClass : delegates[i].getStopIf()) { if (exceptionClass.isAssignableFrom(x.getClass())) { shallContinue = false; break; } } } } lastResult = thisAuth != null && thisAuth.isAuthenticated(); if (lastResult) { authenticated = true; auth = thisAuth; } else { authenticated = false; auth = null; } } else { shallContinue = false; } if (logger.isDebugEnabled()) { logger.debug("Chained Authentication status of " + output + " with manager:" + delegates[i] + "; Authenticated:" + authenticated); } } if (authenticated) { return auth; } else if (lastException != null) { //we had at least one authentication exception, throw it throw lastException; } else { //not authenticated, but return the last of the result return auth; } }
From source file:org.cloudfoundry.identity.uaa.authentication.manager.ExternalLoginAuthenticationManager.java
protected UaaUser getUser(Authentication request, ExternalAuthenticationDetails authDetails) { UserDetails userDetails;//from w ww .j a v a 2s . c om if (request.getPrincipal() instanceof UserDetails) { userDetails = (UserDetails) request.getPrincipal(); } else if (request instanceof UsernamePasswordAuthenticationToken) { String username = request.getPrincipal().toString(); String password = request.getCredentials() != null ? request.getCredentials().toString() : ""; userDetails = new User(username, password, true, true, true, true, UaaAuthority.USER_AUTHORITIES); } else if (request.getPrincipal() == null) { logger.debug(this.getClass().getName() + "[" + name + "] cannot process null principal"); return null; } else { logger.debug(this.getClass().getName() + "[" + name + "] cannot process request of type: " + request.getClass().getName()); return null; } String name = userDetails.getUsername(); String email = null; if (userDetails instanceof Mailable) { email = ((Mailable) userDetails).getEmailAddress(); if (name == null) { name = email; } } if (email == null) { email = generateEmailIfNull(name); } String givenName = null; String familyName = null; if (userDetails instanceof Named) { Named names = (Named) userDetails; givenName = names.getGivenName(); familyName = names.getFamilyName(); } String phoneNumber = (userDetails instanceof DialableByPhone) ? ((DialableByPhone) userDetails).getPhoneNumber() : null; String externalId = (userDetails instanceof ExternallyIdentifiable) ? ((ExternallyIdentifiable) userDetails).getExternalId() : name; UaaUserPrototype userPrototype = new UaaUserPrototype().withUsername(name).withPassword("").withEmail(email) .withAuthorities(UaaAuthority.USER_AUTHORITIES).withGivenName(givenName).withFamilyName(familyName) .withCreated(new Date()).withModified(new Date()).withOrigin(origin).withExternalId(externalId) .withZoneId(IdentityZoneHolder.get().getId()).withPhoneNumber(phoneNumber); return new UaaUser(userPrototype); }
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();//w ww. j av a 2 s. com @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.authentication.manager.UsernamePasswordExtractingAuthenticationManager.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (authentication == null) { return authentication; }/*from w w w.j a v a2 s. c o m*/ UsernamePasswordAuthenticationToken output = null; if (authentication instanceof UsernamePasswordAuthenticationToken) { output = (UsernamePasswordAuthenticationToken) authentication; } else { output = new UsernamePasswordAuthenticationToken(authentication, authentication.getCredentials(), authentication.getAuthorities()); output.setAuthenticated(authentication.isAuthenticated()); output.setDetails(authentication.getDetails()); } return delegate.authenticate(output); }