List of usage examples for org.springframework.security.core Authentication getCredentials
Object getCredentials();
From source file:org.cloudfoundry.identity.uaa.ldap.PasswordComparisonAuthenticator.java
@Override public DirContextOperations authenticate(Authentication authentication) { DirContextOperations user = null;// w ww . jav a 2 s .co m 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, username); } if (logger.isDebugEnabled()) { logger.debug("Performing LDAP compare of password attribute '" + passwordAttributeName + "' for user '" + user.getDn() + "'"); } if (isLocalCompare()) { localCompareAuthenticate(user, password); } else { String encodedPassword = passwordEncoder.encodePassword(password, null); byte[] passwordBytes = Utf8.encode(encodedPassword); searchAuthenticate(user, passwordBytes, ldapTemplate); } return user; }
From source file:org.cloudfoundry.identity.uaa.provider.ldap.PasswordComparisonAuthenticator.java
@Override public DirContextOperations authenticate(Authentication authentication) { DirContextOperations user = null;/*from ww w. j a va 2s . c o m*/ 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 (isLocalCompare()) { localCompareAuthenticate(user, password); } else { String encodedPassword = passwordEncoder.encodePassword(password, null); byte[] passwordBytes = Utf8.encode(encodedPassword); searchAuthenticate(user, passwordBytes, ldapTemplate); } return user; }
From source file:org.cloudifysource.security.CloudifyDaoAuthenticationProvider.java
@Override public Authentication authenticate(final Authentication authentication) throws AuthenticationException { Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports", "Only UsernamePasswordAuthenticationToken is supported")); logger.finest("CloudifyDaoAuthenticationProvider: authenticate"); final UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken) authentication; final CloudifyUserDetails user; // Determine username final String username = userToken.getName(); final String password = (String) authentication.getCredentials(); if (StringUtils.isBlank(username)) { throw new IllegalArgumentException("Empty username not allowed"); }/* w ww . ja va 2s . com*/ Assert.notNull(password, "Null password was supplied in authentication token"); logger.fine("Processing authentication request for user: " + username); // Get the Cloudify user details from the user details service try { user = retrieveUser(username); String retrievedUserPassword = user.getPassword(); if (!password.equals(retrievedUserPassword)) { logger.warning("Authentication failed: password does not match stored value"); throw new BadCredentialsException(messages .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } } catch (final UsernameNotFoundException e) { logger.warning("User '" + username + "' not found"); throw e; } // authenticate runAuthenticationChecks(user); // create a successful and full authentication token return createSuccessfulAuthentication(userToken, user); }
From source file:org.dspace.app.rest.security.EPersonRestAuthenticationProvider.java
private Authentication authenticateNewLogin(Authentication authentication) { Context newContext = null;/*from w ww . j a v a2 s .c om*/ Authentication output = null; if (authentication != null) { try { newContext = new Context(); String name = authentication.getName(); String password = Objects.toString(authentication.getCredentials(), null); int implicitStatus = authenticationService.authenticateImplicit(newContext, null, null, null, request); if (implicitStatus == AuthenticationMethod.SUCCESS) { log.info(LogManager.getHeader(newContext, "login", "type=implicit")); output = createAuthentication(password, newContext); } else { int authenticateResult = authenticationService.authenticate(newContext, name, password, null, request); if (AuthenticationMethod.SUCCESS == authenticateResult) { log.info(LogManager.getHeader(newContext, "login", "type=explicit")); output = createAuthentication(password, newContext); } else { log.info(LogManager.getHeader(newContext, "failed_login", "email=" + name + ", result=" + authenticateResult)); throw new BadCredentialsException("Login failed"); } } } finally { if (newContext != null && newContext.isValid()) { try { newContext.complete(); } catch (SQLException e) { log.error(e.getMessage() + " occurred while trying to close", e); } } } } return output; }
From source file:org.egov.infstr.security.spring.filter.CustomLogoutHandler.java
private void auditLogout(final Authentication authentication) { if (authentication != null) { final String systemAuditId = ((HashMap<String, String>) authentication.getCredentials()) .get(SecurityConstants.LOGIN_LOG_ID); if (StringUtils.isNotBlank(systemAuditId)) { final SystemAudit systemAudit = systemAuditService.getSystemAuditById(Long.valueOf(systemAuditId)); systemAudit.setLogoutTime(new Date()); systemAuditService.createOrUpdateSystemAudit(systemAudit); }// w w w.j av a2 s. c o m } }
From source file:org.fao.geonet.kernel.security.ecas.ECasAuthenticationProvider.java
public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (!supports(authentication.getClass())) { return null; }//ww w . j a v a2 s . co m if (authentication instanceof UsernamePasswordAuthenticationToken && (!CasAuthenticationFilter.CAS_STATEFUL_IDENTIFIER .equals(authentication.getPrincipal().toString()) && !CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER .equals(authentication.getPrincipal().toString()))) { // UsernamePasswordAuthenticationToken not CAS related return null; } // If an existing CasAuthenticationToken, just check we created it if (authentication instanceof CasAuthenticationToken) { if (this.key.hashCode() == ((CasAuthenticationToken) authentication).getKeyHash()) { return authentication; } else { throw new BadCredentialsException(messages.getMessage("CasAuthenticationProvider.incorrectKey", "The presented CasAuthenticationToken does not contain the expected key")); } } // Ensure credentials are presented if ((authentication.getCredentials() == null) || "".equals(authentication.getCredentials())) { throw new BadCredentialsException(messages.getMessage("CasAuthenticationProvider.noServiceTicket", "Failed to provide a CAS service ticket to validate")); } boolean stateless = false; if (authentication instanceof UsernamePasswordAuthenticationToken && CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER.equals(authentication.getPrincipal())) { stateless = true; } CasAuthenticationToken result = null; if (stateless) { // Try to obtain from cache result = statelessTicketCache.getByTicketId(authentication.getCredentials().toString()); } if (result == null) { result = this.authenticateNow(authentication); result.setDetails(authentication.getDetails()); } if (stateless) { // Add to cache statelessTicketCache.putTicketInCache(result); } return result; }
From source file:org.fao.geonet.kernel.security.ecas.ECasAuthenticationProvider.java
private CasAuthenticationToken authenticateNow(final Authentication authentication) throws AuthenticationException { try {/* ww w .j a v a2s . co m*/ final Assertion assertion = this.ticketValidator.validate(authentication.getCredentials().toString(), getServiceUrl(authentication)); final UserDetails userDetails = loadUserByAssertion(assertion); userDetailsChecker.check(userDetails); return new CasAuthenticationToken(this.key, userDetails, authentication.getCredentials(), authoritiesMapper.mapAuthorities(userDetails.getAuthorities()), userDetails, assertion); } catch (final TicketValidationException e) { throw new BadCredentialsException(e.getMessage(), e); } }
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. * /* w w w .j av a 2s . c o m*/ * @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.ui.security.UISessionInitializationStrategy.java
public void onAuthentication(Authentication authentication, HttpServletRequest request, HttpServletResponse response) throws SessionAuthenticationException { super.onAuthentication(authentication, request, response); final boolean debug = log.isDebugEnabled(); if (debug)/*from w w w. j a v a 2 s . c om*/ log.debug("Initializing UI session parameters..."); HttpSession session = request.getSession(); WebUser webUser = (WebUser) session.getAttribute(Constants.WEBUSER_SES_ATTR); assert (webUser != null); // At this point webUser should never be null if (webUser.getPreferences().getKeys().size() == 0) { // will be cleaned out during registration session.setAttribute(Constants.PASSWORD_SES_ATTR, authentication.getCredentials().toString()); session.setAttribute(Constants.NEEDS_REGISTRATION, Boolean.TRUE); if (debug) log.debug("Stashing registration parameters in the session for later use"); } ServletContext ctx = session.getServletContext(); // Load up the user's dashboard preferences loadDashboard(ctx, webUser, authzBoss); // Determine if we can render chart images setXlibFlag(session); }
From source file:org.infoscoop.api.oauth2.provider.ISAuthenticationProvider.java
@Override public Authentication authenticate(Authentication auth) throws AuthenticationException { String userid = auth.getName(); String password = auth.getCredentials().toString(); AuthenticationService service = AuthenticationService.getInstance(); try {// w ww . j a v a 2 s.c o m // login service.login(userid, password); // authority List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>(); PortalAdminsService portalService = PortalAdminsService.getHandle(); portalService.getPortalAdmins(); Portaladmins admin = portalService.getPortalAdmin(userid); if (admin != null) { grantedAuths.add(new SimpleGrantedAuthority(ROLE_ADMIN)); } else { grantedAuths.add(new SimpleGrantedAuthority(ROLE_USER)); } if (log.isDebugEnabled()) log.debug("complete login " + userid + " - authotiry:" + grantedAuths.toString()); return new UsernamePasswordAuthenticationToken(userid, password, grantedAuths); } catch (AuthenticationException e) { // login error log.error(e); e.printStackTrace(); return null; } catch (org.infoscoop.account.AuthenticationException e) { log.error(e); e.printStackTrace(); return null; } catch (Exception ex) { log.error(ex); ex.printStackTrace(); return null; } }