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) 

Source Link

Document

Constructs a UsernameNotFoundException with the specified message.

Usage

From source file:org.nimbustools.messaging.query.security.NimbusAuthzUserDetailsService.java

public QueryUser loadUserByDn(String dn) throws UsernameNotFoundException, DataAccessException {

    if (dn == null) {
        throw new IllegalArgumentException("dn may not be null");
    }/*from w  ww.  j ava2  s.c  om*/

    try {
        final String userId = authzDBAdapter.getCanonicalUserIdFromDn(dn);
        final List<UserAlias> aliasList = authzDBAdapter.getUserAliases(userId);

        String accessId = null;
        String secret = null;

        for (UserAlias alias : aliasList) {
            if (alias.getAliasType() == AuthzDBAdapter.ALIAS_TYPE_S3) {
                if (accessId == null) {
                    secret = alias.getAliasTypeData();
                    accessId = alias.getAliasName();
                } else {
                    logger.warn(String.format(
                            "Found multiple query user aliases for canonical user %s. Using the first one (%s)",
                            userId, accessId));
                }
            }
        }

        if (secret == null || accessId == null) {
            throw new UsernameNotFoundException("User DN '" + dn + "' does not map to query credentials");
        }

        return new QueryUser(accessId, secret, dn);

    } catch (AuthzDBException e) {
        throw new UsernameNotFoundException("Failed to retrieve query credentials for DN '" + dn + "'", e);
    }
}

From source file:org.opencastproject.kernel.userdirectory.UserAndRoleDirectoryServiceImpl.java

/**
 * {@inheritDoc}//from  ww w  .  j  ava  2s  .c om
 *
 * @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
 */
@Override
public UserDetails loadUserByUsername(String userName)
        throws UsernameNotFoundException, org.springframework.dao.DataAccessException {
    User user = loadUser(userName);
    if (user == null)
        throw new UsernameNotFoundException(userName);

    // Store the user in the security service
    securityService.setUser(user);

    Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
    for (Role role : user.getRoles()) {
        authorities.add(new SimpleGrantedAuthority(role.getName()));
    }

    // Add additional roles from role providers
    for (RoleProvider roleProvider : roleProviders) {
        List<Role> rolesForUser = roleProvider.getRolesForUser(userName);
        for (Role role : rolesForUser)
            authorities.add(new SimpleGrantedAuthority(role.getName()));
    }

    authorities.add(new SimpleGrantedAuthority(securityService.getOrganization().getAnonymousRole()));
    // need a non null password to instantiate org.springframework.security.core.userdetails.User
    // but CAS authenticated users have no password
    String password = user.getPassword() == null ? DEFAULT_PASSWORD : user.getPassword();
    return new org.springframework.security.core.userdetails.User(user.getUsername(), password, user.canLogin(),
            true, true, true, authorities);

}

From source file:org.opendatakit.common.security.spring.Oauth2AuthenticationProvider.java

/**
 * Handles the creation of the final <tt>Authentication</tt> object which will be returned by the provider.
 * <p>// w  w  w  .ja v  a  2 s .co m
 * The default implementation just creates a new OutOfBandAuthenticationToken from the original, but with the
 * UserDetails as the principal and including the authorities loaded by the UserDetailsService.
 *
 * @param userDetails the loaded UserDetails object
 * @param auth the token passed to the authenticate method, containing
 * @return the token which will represent the authenticated user.
 */
protected Authentication createSuccessfulAuthentication(UserDetails rawUserDetails,
        Oauth2AuthenticationToken auth) {
    String eMail = auth.getEmail();
    if (eMail == null) {
        logger.warn("User account attributes did not include an e-mail address! ");
        throw new UsernameNotFoundException("email address not supplied in User account attributes");
    }
    eMail = Oauth2AuthenticationProvider.normalizeMailtoAddress(eMail);
    String mailtoDomain = Oauth2AuthenticationProvider.getMailtoDomain(eMail);

    UserDetails userDetails = rawUserDetails;

    Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();

    authorities.addAll(userDetails.getAuthorities());
    // add the AUTH_GOOGLE_OAUTH2 granted authority,
    authorities.add(new SimpleGrantedAuthority(GrantedAuthorityName.AUTH_GOOGLE_OAUTH2.toString()));

    // attempt to look user up in registered users table...
    String username = null;
    UserDetails partialDetails = null;
    boolean noRights = false;
    try {
        partialDetails = wrappingUserDetailsService.loadUserByUsername(eMail);
        // found the user in the table -- fold in authorizations and get uriUser.
        authorities.addAll(partialDetails.getAuthorities());
        // users are blacklisted by registering them and giving them no rights.
        noRights = partialDetails.getAuthorities().isEmpty();
        username = partialDetails.getUsername();
    } catch (Exception e) {
        logger.warn("Oauth2 attribute e-mail: " + eMail + " did not match any known e-mail addresses! "
                + e.getMessage());
        throw new UsernameNotFoundException("account not recognized");
    }

    AggregateUser trueUser = new AggregateUser(username, partialDetails.getPassword(),
            UUID.randomUUID().toString(), // junk...
            mailtoDomain, partialDetails.isEnabled(), partialDetails.isAccountNonExpired(),
            partialDetails.isCredentialsNonExpired(), partialDetails.isAccountNonLocked(), authorities);
    if (noRights
            || !(trueUser.isEnabled() && trueUser.isAccountNonExpired() && trueUser.isAccountNonLocked())) {
        logger.warn("Oauth2 attribute e-mail: " + eMail + " account is blocked! ");
        throw new UsernameNotFoundException("account is blocked");
    }

    return new Oauth2AuthenticationToken(trueUser, trueUser.getAuthorities(), auth.getAccessToken(),
            auth.getEmail(), auth.getExpiration());
}

From source file:org.opendatakit.common.security.spring.OutOfBandAuthenticationProvider.java

/**
 * Handles the creation of the final <tt>Authentication</tt> object which will be returned by the provider.
 * <p>/*from  ww  w . j  a v  a  2s .  c o m*/
 * The default implementation just creates a new OutOfBandAuthenticationToken from the original, but with the
 * UserDetails as the principal and including the authorities loaded by the UserDetailsService.
 *
 * @param userDetails the loaded UserDetails object
 * @param auth the token passed to the authenticate method, containing
 * @return the token which will represent the authenticated user.
 */
protected Authentication createSuccessfulAuthentication(UserDetails rawUserDetails,
        OutOfBandAuthenticationToken auth) {
    String eMail = auth.getEmail();
    if (eMail == null) {
        logger.warn("OutOfBand attributes did not include an e-mail address! ");
        throw new UsernameNotFoundException("email address not supplied in OutOfBand attributes");
    }
    eMail = OutOfBandAuthenticationProvider.normalizeMailtoAddress(eMail);
    String mailtoDomain = OutOfBandAuthenticationProvider.getMailtoDomain(eMail);

    UserDetails userDetails = rawUserDetails;

    Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();

    authorities.addAll(userDetails.getAuthorities());
    // add the AUTH_OUT_OF_BAND granted authority,
    authorities.add(new SimpleGrantedAuthority(GrantedAuthorityName.AUTH_OUT_OF_BAND.toString()));

    // attempt to look user up in registered users table...
    String username = null;
    UserDetails partialDetails = null;
    boolean noRights = false;
    try {
        partialDetails = wrappingUserDetailsService.loadUserByUsername(eMail);
        // found the user in the table -- fold in authorizations and get uriUser.
        authorities.addAll(partialDetails.getAuthorities());
        // users are blacklisted by registering them and giving them no rights.
        noRights = partialDetails.getAuthorities().isEmpty();
        username = partialDetails.getUsername();
    } catch (Exception e) {
        logger.warn("OutOfBand attribute e-mail: " + eMail + " did not match any known e-mail addresses! "
                + e.getMessage());
        throw new UsernameNotFoundException("account not recognized");
    }

    AggregateUser trueUser = new AggregateUser(username, partialDetails.getPassword(),
            UUID.randomUUID().toString(), // junk...
            mailtoDomain, partialDetails.isEnabled(), partialDetails.isAccountNonExpired(),
            partialDetails.isCredentialsNonExpired(), partialDetails.isAccountNonLocked(), authorities);
    if (noRights
            || !(trueUser.isEnabled() && trueUser.isAccountNonExpired() && trueUser.isAccountNonLocked())) {
        logger.warn("OutOfBand attribute e-mail: " + eMail + " account is blocked! ");
        throw new UsernameNotFoundException("account is blocked");
    }

    return new OutOfBandAuthenticationToken(trueUser, trueUser.getAuthorities(), auth.getEmail());
}

From source file:org.opendatakit.common.security.spring.WrappingOpenIDAuthenticationProvider.java

@Override
protected Authentication createSuccessfulAuthentication(UserDetails rawUserDetails,
        OpenIDAuthenticationToken auth) {
    String eMail = null;//from   w  ww.j ava 2s  .c o  m
    List<OpenIDAttribute> oAttrList = auth.getAttributes();
    for (OpenIDAttribute oAttr : oAttrList) {
        if ("email".equals(oAttr.getName())) {
            Object o = oAttr.getValues().get(0);
            if (o != null) {
                eMail = (String) o;
            }
        }
    }
    if (eMail == null) {
        logger.warn("OpenId attributes did not include an e-mail address! ");
        throw new UsernameNotFoundException("email address not supplied in OpenID attributes");
    }
    eMail = WrappingOpenIDAuthenticationProvider.normalizeMailtoAddress(eMail);
    String mailtoDomain = WrappingOpenIDAuthenticationProvider.getMailtoDomain(eMail);

    UserDetails userDetails = rawUserDetails;

    Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();

    authorities.addAll(userDetails.getAuthorities());
    // add the AUTH_OPENID granted authority,
    authorities.add(new SimpleGrantedAuthority(GrantedAuthorityName.AUTH_OPENID.toString()));

    // attempt to look user up in registered users table...
    String username = null;
    UserDetails partialDetails = null;
    boolean noRights = false;
    try {
        partialDetails = wrappingUserDetailsService.loadUserByUsername(eMail);
        // found the user in the table -- fold in authorizations and get uriUser.
        authorities.addAll(partialDetails.getAuthorities());
        // users are blacklisted by registering them and giving them no rights.
        noRights = partialDetails.getAuthorities().isEmpty();
        username = partialDetails.getUsername();
    } catch (Exception e) {
        e.printStackTrace();
        logger.warn("OpenId attribute e-mail: " + eMail + " did not match any known e-mail addresses! "
                + e.getMessage());
        throw new UsernameNotFoundException("account not recognized");
    }

    AggregateUser trueUser = new AggregateUser(username, partialDetails.getPassword(),
            UUID.randomUUID().toString(), // junk...
            mailtoDomain, partialDetails.isEnabled(), partialDetails.isAccountNonExpired(),
            partialDetails.isCredentialsNonExpired(), partialDetails.isAccountNonLocked(), authorities);
    if (noRights
            || !(trueUser.isEnabled() && trueUser.isAccountNonExpired() && trueUser.isAccountNonLocked())) {
        logger.warn("OpenId attribute e-mail: " + eMail + " account is blocked! ");
        throw new UsernameNotFoundException("account is blocked");
    }

    return new OpenIDAuthenticationToken(trueUser, trueUser.getAuthorities(), auth.getIdentityUrl(),
            auth.getAttributes());
}

From source file:org.opendaylight.controller.usermanager.internal.UserManager.java

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    AuthenticatedUser user = activeUsers.get(username);

    if (user != null) {
        boolean enabled = true;
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = true;

        return new User(username, localUserConfigList.get(username).getPassword(), enabled, accountNonExpired,
                credentialsNonExpired, accountNonLocked, user.getGrantedAuthorities(getUserLevel(username)));
    } else {//from  w  w  w  .j a va2  s  . c o m
        throw new UsernameNotFoundException("User not found " + username);
    }
}

From source file:org.orcid.core.security.OrcidUserDetailsService.java

/**
 * Locates the user based on the username. In the actual implementation, the
 * search may possibly be case insensitive, or case insensitive depending on
 * how the implementation instance is configured. In this case, the
 * <code>UserDetails</code> object that comes back may have a username that
 * is of a different case than what was actually requested..
 * /*from   w  ww. j ava 2  s  .  c om*/
 * @param username
 *            the username identifying the user whose data is required.
 * @return a fully populated user record (never <code>null</code>)
 * @throws org.springframework.security.core.userdetails.UsernameNotFoundException
 *             if the user could not be found or the user has no
 *             GrantedAuthority
 */
@Override
@Transactional(propagation = Propagation.REQUIRED)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    LOGGER.info("About to load user by username = {}", username);
    ProfileEntity profile = obtainEntity(username);

    if (profile == null) {
        throw new UsernameNotFoundException("Bad username or password");
    }
    if (profile.getPrimaryRecord() != null) {
        throw new DeprecatedProfileException("orcid.frontend.security.deprecated_with_primary",
                profile.getPrimaryRecord().getId(), profile.getId());
    }
    if (!profile.getClaimed() && !securityMgr.isAdmin()) {
        throw new UnclaimedProfileExistsException("orcid.frontend.security.unclaimed_exists");
    }
    if (profile.getDeactivationDate() != null && !securityMgr.isAdmin()) {
        throw new DisabledException("Account not active, please call helpdesk");
    }

    String primaryEmail = null;

    // Clients doesnt have primary email, so, we need to cover that case.
    if (profile.getPrimaryEmail() != null)
        primaryEmail = profile.getPrimaryEmail().getId();

    OrcidProfileUserDetails userDetails = null;

    if (profile.getOrcidType() != null) {
        userDetails = new OrcidProfileUserDetails(profile.getId(), primaryEmail, profile.getEncryptedPassword(),
                profile.getOrcidType(), profile.getGroupType());
    } else {
        userDetails = new OrcidProfileUserDetails(profile.getId(), primaryEmail,
                profile.getEncryptedPassword());
    }

    return userDetails;
}

From source file:org.patientview.radar.service.impl.UserManagerImpl.java

public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException, DataAccessException {
    // Pull the user from the DAO
    User user = userDao.getProfessionalUser(email);
    if (user != null) {
        return user;
    }/*from  w w  w.  j  a  v  a  2  s.  c om*/
    throw new UsernameNotFoundException("User not found with email address " + email);
}

From source file:org.pentaho.platform.plugin.services.security.userrole.memory.PentahoUserMap.java

/**
 * Locates the specified user by performing a case insensitive search by username.
 *
 * @param username to find/*from  w w  w  .jav 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);
    }

    return result;
}

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;//from w w w  . j a  va2 s  . 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 (usePasswordAttrCompare && isPasswordAttrCompare(user, password)) {
        return user;
    } else if (isLdapPasswordCompare(user, ldapTemplate, password)) {
        return user;
    }
    throw new BadCredentialsException(
            messages.getMessage("PasswordComparisonAuthenticator.badCredentials", "Bad credentials"));
}