Example usage for org.springframework.security.core.userdetails UsernameNotFoundException UsernameNotFoundException

List of usage examples for org.springframework.security.core.userdetails UsernameNotFoundException UsernameNotFoundException

Introduction

In this page you can find the example usage for org.springframework.security.core.userdetails UsernameNotFoundException UsernameNotFoundException.

Prototype

public UsernameNotFoundException(String msg, Throwable t) 

Source Link

Document

Constructs a UsernameNotFoundException with the specified message and root cause.

Usage

From source file:iplatform.admin.ui.server.auth.ad.ActiveDirectoryLdapAuthenticationProvider.java

@SuppressWarnings("deprecation")
private DirContextOperations searchForUser(DirContext ctx, String username) throws NamingException {
    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    String searchFilter = "(&(objectClass=user)(userPrincipalName={0}))";

    final String bindPrincipal = createBindPrincipal(username);

    String searchRoot = rootDn != null ? rootDn : searchRootFromPrincipal(bindPrincipal);

    try {//from  www . ja va  2s  . co m
        return SpringSecurityLdapTemplate.searchForSingleEntryInternal(ctx, searchCtls, searchRoot,
                searchFilter, new Object[] { bindPrincipal });
    } catch (IncorrectResultSizeDataAccessException incorrectResults) {
        if (incorrectResults.getActualSize() == 0) {
            UsernameNotFoundException userNameNotFoundException = new UsernameNotFoundException(
                    "User " + username + " not found in directory.", username);
            userNameNotFoundException.initCause(incorrectResults);
            throw badCredentials(userNameNotFoundException);
        }
        // Search should never return multiple results if properly configured, so just rethrow
        throw incorrectResults;
    }
}

From source file:org.air.standard.security.UserDetailsServiceImpl.java

@Override
public Object loadUserBySAML(final SAMLCredential samlCred) throws UsernameNotFoundException {

    CoreStandardSbacUser user = null;//from  w  w w  . j a v  a2s .  com
    try {
        final String[] pipeDelimitedChain = samlCred.getAttributeAsStringArray(SBAC_TENANCY_CHAIN_KEY);
        System.out.println("tenant chain:" + pipeDelimitedChain);

        final Map<String, String> userAtts = extractUserAttributes(samlCred);
        user = (CoreStandardSbacUser) rolesAndPermissionsService.createUser(pipeDelimitedChain, userAtts,
                CoreStandardSbacUser.class);

    } catch (final Exception e) {
        final String referenceNumber = String.valueOf(RandomUtils.nextInt(MAX_ERROR_CODE));
        _logger.error("failure processing user, reference number: " + referenceNumber, e);
        throw new UsernameNotFoundException("Unable to process user, reference number: " + referenceNumber, e);
    }

    try {
        // lets create a new sessionKey.
        AuthorizationDAO dao = new AuthorizationDAO();

        // generate a unique identifier.
        // todo: not sure if we need to make a DB call for this.
        String sessionKey = dao.generateNewSessionKey();

        // now insert a session into the table for this user.
        // todo: instead of CSR_Administrator we need to insert the
        // appropriate OpenAM roles - one record for each role.
        dao.addSessionForUser(user.getUsername(), sessionKey, "Admin");
        user.setSessionId(sessionKey);
    } catch (SQLException exp) {
        _logger.error(exp.getMessage());
        _logger.error(exp.getStackTrace().toString());
        // todo: Fix this so that it returns a proper message.
    }
    return user;
}

From source file:org.apache.ambari.server.security.ldap.AmbariLdapDataPopulator.java

/**
 * Checks LDAP configuration for changes and reloads LDAP template if they occurred.
 *
 * @return LdapTemplate instance/*from ww  w  .ja  va2 s. co  m*/
 */
protected LdapTemplate loadLdapTemplate() {
    final LdapServerProperties properties = configuration.getLdapServerProperties();
    if (ldapTemplate == null || !properties.equals(ldapServerProperties)) {
        LOG.info("Reloading properties");
        ldapServerProperties = properties;

        final LdapContextSource ldapContextSource = createLdapContextSource();
        final List<String> ldapUrls = ldapServerProperties.getLdapUrls();
        ldapContextSource.setUrls(ldapUrls.toArray(new String[ldapUrls.size()]));

        if (!ldapServerProperties.isAnonymousBind()) {
            ldapContextSource.setUserDn(ldapServerProperties.getManagerDn());
            ldapContextSource.setPassword(ldapServerProperties.getManagerPassword());
        }

        try {
            ldapContextSource.afterPropertiesSet();
        } catch (Exception e) {
            LOG.error("LDAP Context Source not loaded ", e);
            throw new UsernameNotFoundException("LDAP Context Source not loaded", e);
        }

        ldapContextSource.setReferral(ldapServerProperties.getReferralMethod());

        ldapTemplate = createLdapTemplate(ldapContextSource);

        ldapTemplate.setIgnorePartialResultException(true);
    }
    return ldapTemplate;
}

From source file:org.apache.ranger.service.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;//from www  .ja  v a 2  s  .c  o m
    String username = authentication.getName();
    String password = (String) authentication.getCredentials();

    Iterator dns = getUserDns(username).iterator();

    SpringSecurityLdapTemplate ldapTemplate = new SpringSecurityLdapTemplate(getContextSource());

    while (dns.hasNext() && user == null) {
        final String userDn = (String) dns.next();

        try {
            user = ldapTemplate.retrieveEntry(userDn, getUserAttributes());
        } catch (NameNotFoundException ignore) {
        }
    }

    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() + "'");
    }

    String encodedPassword = passwordEncoder.encodePassword(password, null);
    byte[] passwordBytes = encodedPassword.getBytes();

    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.ldap.PasswordComparisonAuthenticator.java

@Override
public DirContextOperations authenticate(Authentication authentication) {
    DirContextOperations user = null;//  ww  w  . j av  a2 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.fao.geonet.kernel.security.ldap.LdapUserDetailsManager.java

private DirContextAdapter loadUserAsContext(final DistinguishedName dn, final String username) {
    return (DirContextAdapter) template.executeReadOnly(new ContextExecutor() {
        public Object executeWithContext(DirContext ctx) throws NamingException {
            try {
                Attributes attrs = ctx.getAttributes(dn, attributesToRetrieve);
                return new DirContextAdapter(attrs, LdapUtils.getFullDn(dn, ctx));
            } catch (NameNotFoundException notFound) {
                throw new UsernameNotFoundException("User " + username + " not found", notFound);
            }//w  w  w  . ja  v a  2 s  . co  m
        }
    });
}

From source file:org.jasig.ssp.service.impl.ScheduledTaskWrapperServiceImpl.java

/**
 * Decorates the given {@code Runnable} with a login and logout of
 * {@link org.jasig.ssp.service.SecurityService#noAuthAdminUser()}.
 *
 * <p>Prior to <a href="https://issues.jasig.org/browse/SSP-2241">SSP-2241</a>
 * we didn't attempt to ensure any particular {@link SecurityContext} state
 * prior to running jobs. This ended up causing a memory leak because our
 * Hibernate flush interceptor would generate a new {@link SspUser} for
 * every flushed "auditer" field, and every time that happened, that
 * {@link SspUser} was added to a {@code ThreadLocal} list. For a large
 * job like {@link #syncExternalPersons()}, the growth of that list was
 * particularly explosive. {@link SspUser} is definitely due for a refactor
 * to eliminate it's {@code ThreadLocal} dependencies, but for the time
 * being we're able to short-circuit the leak by ensuring that there is
 * a current {@link Authentication} that the Hibernate flush interceptor
 * will honor. (It will not honor the anonymous user.) And this is good
 * practice anyway - to always explicitly set up a security context rather
 * than let obscure Hibernate extension internals make up the rules as we
 * go.</p>/* w  w w .  j ava2s . c om*/
 *
 * @see #withMaybeSudo(Runnable)
 * @param work
 * @return
 * @throws AuthenticationException
 */
protected Runnable withSudo(final Runnable work, final UUID runAsId) throws AuthenticationException {
    return new Runnable() {
        @Override
        public void run() {
            final SspUser runAs;
            if (runAsId == null) {
                runAs = securityService.noAuthAdminUser();
            } else {
                try {
                    final Person person = personService.get(runAsId);
                    if (person == null) {
                        throw new ObjectNotFoundException(runAsId, Person.class.getName());
                    }

                    // mostly copy/paste from UPortalSecurityFilter
                    final Set<Assignment> assignments = PermissionsService.IMPL.get()
                            .getAssignmentsForPerson(person.getUsername(), true);

                    // Find SSP-related permissions in the assignments collection
                    final Set<GrantedAuthority> authorities = Sets.newHashSet();
                    for (Assignment a : assignments) {
                        if (a.getOwner().getKey().equals(UPortalSecurityFilter.SSP_OWNER)) {
                            // This one pertains to us...
                            String activity = a.getActivity().getKey();
                            authorities.add(new GrantedAuthorityImpl("ROLE_" + activity));
                        }
                    }

                    final SspUser user = new SspUser(person.getUsername(), "", true, true, true, true,
                            authorities);

                    user.setPerson(person);
                    runAs = user;
                } catch (ObjectNotFoundException e) {
                    throw new UsernameNotFoundException("Could not find Person by ID [" + runAsId + "]", e);
                }

            }
            Authentication auth = new RunAsUserToken(runAsKey, runAs, null, runAs.getAuthorities(), null);
            auth = authenticationManager.authenticate(auth);

            // Not sure why/if we need this. Just trying to mimic long-time
            // legacy behavior in UPortalPreAuthenticatedProcessingFilter
            if (eventPublisher != null) {
                eventPublisher.publishEvent(new AuthenticationSuccessEvent(auth));
            }

            // AuthenticationManager doesn't do this for you
            SecurityContextHolder.getContext().setAuthentication(auth);

            try {
                work.run();
            } finally {
                SecurityContextHolder.getContext().setAuthentication(null);
            }
        }
    };
}

From source file:org.josso.spring.security.JOSSOUserDetailsService.java

/**
 * This implementation will retrieve user details from JOSSO services.
 *///from ww  w  .j  a va 2s. c  o  m
public UserDetails loadUserByUsername(String username)
        throws UsernameNotFoundException, org.springframework.dao.DataAccessException {
    try {
        // NOTE: Assuming that the username is actually user's single sign-on session since the operation for
        // fetching users in the security domain has not been implemented in the JOSSO binding capability.
        //
        // Consequently, it will not work within a JavaEE preauthenticated setting against an IdP built on JOSSO 2.3
        // since a principal name will be supplied instead of a single sign-on session identifier.
        SSOUser user = getIdentityManager().findUserInSession(_requester, username);
        //SSOUser user = getIdentityManager().findUser(_requester, "", username);
        SSORole[] roles = _im.findRolesBySSOSessionId(_requester, username);
        return toUserDetails(user, roles);
    } catch (NoSuchUserException e) {
        logger.error(e.getMessage(), e);
        throw new UsernameNotFoundException(e.getMessage(), e);
    } catch (SSOIdentityException e) {
        logger.error(e.getMessage(), e);
        throw new UsernameNotFoundException(e.getMessage(), e);
    }
}

From source file:org.opentestsystem.shared.security.service.UserDetailsServiceImpl.java

@Override
public Object loadUserBySAML(final SAMLCredential samlCred) throws UsernameNotFoundException {
    SbacUser user = null;/*from  w w  w  . jav a 2s.c  o  m*/
    try {
        final String[] pipeDelimitedChain = samlCred.getAttributeAsStringArray(SBAC_TENANCY_CHAIN_KEY);
        LOGGER.warn("tenant chain:" + Arrays.toString(pipeDelimitedChain));

        final Map<String, String> userAtts = extractUserAttributes(samlCred);
        user = this.rolesAndPermissionsService.createUser(pipeDelimitedChain, userAtts, SbacUser.class);

    } catch (final Exception e) {
        final String referenceNumber = String.valueOf(RandomUtils.nextInt(MAX_ERROR_CODE));
        LOGGER.error("failure processing user, reference number: " + referenceNumber, e);
        throw new UsernameNotFoundException("Unable to process user, reference number: " + referenceNumber, e);
    }

    return user;
}

From source file:org.springframework.security.core.userdetails.memory.UserMap.java

/**
 * Locates the specified user by performing a case insensitive search by username.
 *
 * @param username to find/*from  w w  w  . j  a  v a 2  s  .  c  o m*/
 *
 * @return the located user
 *
 * @throws UsernameNotFoundException if the user could not be found
 */
public UserDetails getUser(String username) throws UsernameNotFoundException {
    UserDetails result = this.userMap.get(username.toLowerCase());

    if (result == null) {
        throw new UsernameNotFoundException("Could not find user: " + username, username);
    }

    return result;
}