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.artifactory.storage.db.security.service.UserGroupServiceImpl.java

@Override
public void updateUser(MutableUserInfo userInfo) {
    try {/*from  ww  w . java  2 s.c  o  m*/
        User originalUser = userGroupsDao.findUserByName(userInfo.getUsername());
        if (originalUser == null) {
            throw new UsernameNotFoundException("Cannot update user with user name '" + userInfo.getUsername()
                    + "' since it does not exists!");
        }
        User updatedUser = userInfoToUser(originalUser.getUserId(), userInfo);
        userGroupsDao.updateUser(updatedUser);
    } catch (SQLException e) {
        throw new StorageException("Failed to update user " + userInfo.getUsername(), e);
    }
}

From source file:org.bibsonomy.webapp.util.spring.security.rememberMeServices.LDAPRememberMeServices.java

@Override
protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request,
        HttpServletResponse response) throws RememberMeAuthenticationException, UsernameNotFoundException {
    if (cookieTokens.length != 5) {
        throw new InvalidCookieException(
                "Cookie token did not contain 5 tokens, but contained '" + Arrays.asList(cookieTokens) + "'");
    }//ww w .  j  a v a 2s .  c o  m

    final String username = cookieTokens[0];

    long tokenExpiryTime = this.getExpiryTime(cookieTokens[3]);

    final UserDetails loadUserByUsername = this.getUserDetailsService().loadUserByUsername(username);
    if (loadUserByUsername instanceof UserAdapter) {
        final UserAdapter adapter = (UserAdapter) loadUserByUsername;
        final User user = adapter.getUser();
        final String ldapID = user.getLdapId();
        final String clearPassword = cookieTokens[2];

        final String expectedTokenSignature = this.makeTokenSignature(
                new String[] { Long.toString(tokenExpiryTime), username, ldapID, clearPassword });
        final String signature = cookieTokens[4];

        if (!expectedTokenSignature.equals(signature)) {
            throw new InvalidCookieException("Cookie token[4] contained signature '" + signature
                    + "' but expected '" + expectedTokenSignature + "'");
        }

        user.setPassword(clearPassword);
        return loadUserByUsername;
    }

    throw new UsernameNotFoundException(""); // TODO
}

From source file:org.cbioportal.security.spring.authentication.googleplus.PortalUserDetailsService.java

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(username), "A username is required");
    // set the username into the global state so other components can find out who
    // logged in or tried to log in most recently
    if (log.isDebugEnabled()) {
        log.debug("loadUserByUsername(), attempting to fetch portal user, email: " + username);
    }/*w  w  w  .  j  a va  2s  .c  o m*/
    PortalUserDetails toReturn = null;
    User user = null;
    try {
        user = securityRepository.getPortalUser(username);
    } catch (Exception e) {
        log.debug("User " + username + " was not found in the cbio users table");
        log.debug("Error:" + e);
    }
    if (user != null && user.isEnabled()) {
        if (log.isDebugEnabled()) {
            log.debug(
                    "loadUserByUsername(), attempting to fetch portal user authorities, username: " + username);
        }
        UserAuthorities authorities = securityRepository.getPortalUserAuthorities(username);
        if (authorities != null) {
            List<GrantedAuthority> grantedAuthorities = AuthorityUtils.createAuthorityList(
                    authorities.getAuthorities().toArray(new String[authorities.getAuthorities().size()]));
            toReturn = new PortalUserDetails(username, grantedAuthorities);
            toReturn.setEmail(user.getEmail());
            toReturn.setName(user.getName());

        }
    }

    // outta here
    if (toReturn == null) {
        if (log.isDebugEnabled()) {
            log.debug("loadUserByUsername(), user and/or user authorities is null, user name: " + username);
        }
        // use the Exception message to attache the username to the request object
        throw new UsernameNotFoundException(username);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("loadUserByUsername(), successfully authenticated user, user name: " + username);
        }
        return toReturn;
    }
}

From source file:org.cbioportal.security.spring.authentication.openID.PortalUserDetailsService.java

/**
 * Implementation of {@code AuthenticationUserDetailsService}
 * which allows full access to the submitted {@code Authentication} object.
 * Used by the OpenIDAuthenticationProvider.
 *//*www  . j  ava 2  s.  c o  m*/
public UserDetails loadUserDetails(OpenIDAuthenticationToken token) throws UsernameNotFoundException {

    // what we return
    PortalUserDetails toReturn = null;

    // get open id
    String id = token.getIdentityUrl();
    id = id.toLowerCase();

    // grab other open id attributes
    String email = null;
    String firstName = null;
    String lastName = null;
    String fullName = null;

    // myopenid does not return attributes in the token
    if (id.indexOf("myopenid") != -1) {
        email = id;
        fullName = id;
    } else {
        try {
            List<OpenIDAttribute> attributes = token.getAttributes();
            for (OpenIDAttribute attribute : attributes) {
                if (attribute.getName().equals("email")) {
                    email = attribute.getValues().get(0);
                    email = email.toLowerCase();
                }
                if (attribute.getName().equals("firstname")) {
                    firstName = attribute.getValues().get(0);
                }
                if (attribute.getName().equals("lastname")) {
                    lastName = attribute.getValues().get(0);
                }
                if (attribute.getName().equals("fullname")) {
                    fullName = attribute.getValues().get(0);
                }
            }
            if (fullName == null) {
                StringBuilder fullNameBldr = new StringBuilder();
                if (firstName != null) {
                    fullNameBldr.append(firstName);
                }
                if (lastName != null) {
                    fullNameBldr.append(" ").append(lastName);
                }
                fullName = fullNameBldr.toString();
            }
        } catch (NullPointerException ex) {
            log.warn("Attribute exchange failed using OpenID " + token.getIdentityUrl() + " for everything");
            fullName = email = token.getIdentityUrl();
        }
    }

    // check if this user exists in our backend db
    try {
        if (log.isDebugEnabled()) {
            log.debug("loadUserDetails(), attempting to fetch portal user, email: " + email);
        }
        User user = securityRepository.getPortalUser(email);
        if (user != null && user.isEnabled()) {
            if (log.isDebugEnabled()) {
                log.debug("loadUserDetails(), attempting to fetch portal user authorities, email: " + email);
            }
            UserAuthorities authorities = securityRepository.getPortalUserAuthorities(email);
            if (authorities != null) {
                List<GrantedAuthority> grantedAuthorities = AuthorityUtils.createAuthorityList(
                        authorities.getAuthorities().toArray(new String[authorities.getAuthorities().size()]));
                toReturn = new PortalUserDetails(id, grantedAuthorities);
                toReturn.setEmail(email);
                toReturn.setName(fullName);
            }
        }
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getMessage());
        } else {
            e.printStackTrace();
        }
    }

    // outta here
    if (toReturn == null) {
        if (log.isDebugEnabled()) {
            log.debug("loadUserDetails(), user and/or user authorities is null, email: " + email);
        }
        throw new UsernameNotFoundException("Error:  Unknown user or account disabled");
    } else {
        if (log.isDebugEnabled()) {
            log.debug("loadUserDetails(), successfully authenticated user, email: " + email);
        }
        return toReturn;
    }
}

From source file:org.cbioportal.security.spring.authentication.saml.SAMLUserDetailsServiceImpl.java

/**
 * Implementation of {@code SAMLUserDetailsService}. Parses user details from given 
 * SAML credential object./* www  . j a va 2 s  .  c  o m*/
 */
@Override
public Object loadUserBySAML(SAMLCredential credential) {
    PortalUserDetails toReturn = null;

    String userId = null;
    // get userid and name: iterate over attributes searching for "mail" and "displayName":
    for (Attribute cAttribute : credential.getAttributes()) {
        log.debug("loadUserBySAML(), parsing attribute - " + cAttribute.toString());
        log.debug("loadUserBySAML(), parsing attribute - " + cAttribute.getName());
        log.debug("loadUserBySAML(), parsing attribute - "
                + credential.getAttributeAsString(cAttribute.getName()));
        if (userId == null && cAttribute.getName().equals(samlIdpMetadataEmailAttributeName)) {
            userId = credential.getAttributeAsString(cAttribute.getName());
            //userid = credential.getNameID().getValue(); needed to support OneLogin...?? Although with OneLogin we haven't gotten this far yet...
        }
    }

    //check if this user exists in our DB
    try {
        //validate parsing:
        if (userId == null) {
            String errorMessage = "loadUserBySAML(), Could not parse the user details from credential message. Expected 'mail' attribute, but attribute was not found. "
                    + " Previous debug messages show which attributes were found and parsed.";
            log.error(errorMessage);
            throw new Exception(errorMessage);
        }

        log.debug("loadUserBySAML(), IDP successfully authenticated user, userid: " + userId);
        log.debug("loadUserBySAML(), now attempting to fetch portal user authorities for userid: " + userId);

        //try to find user in DB
        User user = securityRepository.getPortalUser(userId);
        if (user != null && user.isEnabled()) {
            log.debug("loadUserBySAML(), user is enabled; attempting to fetch portal user authorities, userid: "
                    + userId);

            UserAuthorities authorities = securityRepository.getPortalUserAuthorities(userId);
            if (authorities != null) {
                List<GrantedAuthority> grantedAuthorities = AuthorityUtils.createAuthorityList(
                        authorities.getAuthorities().toArray(new String[authorities.getAuthorities().size()]));
                //add granted authorities:
                toReturn = new PortalUserDetails(userId, grantedAuthorities);
                toReturn.setEmail(userId);
                toReturn.setName(userId);
            }
        } else if (user == null) { // new user
            log.debug("loadUserBySAML(), user authorities is null, userid: " + userId
                    + ". Depending on property always_show_study_group, "
                    + "he could still have default access (to PUBLIC studies)");
            toReturn = new PortalUserDetails(userId, getInitialEmptyAuthoritiesList());
            toReturn.setEmail(userId);
            toReturn.setName(userId);
        } else {
            //user WAS found in DB but has been actively disabled:
            throw new UsernameNotFoundException("Error: Your user access to cBioPortal has been disabled");
        }
        return toReturn;
    } catch (UsernameNotFoundException unnf) {
        //throw this exception, so that the user gets redirected to the error HTML page: 
        throw unnf;
    } catch (Exception e) {
        //other (unexpected) errors: just throw (will result in http 500 page with error message):
        log.error(e.getMessage());
        e.printStackTrace();
        throw new RuntimeException("Error during authentication parsing: " + e.getMessage());
    }
}

From source file:org.cloudfoundry.identity.uaa.provider.ldap.PasswordComparisonAuthenticator.java

@Override
public DirContextOperations authenticate(Authentication authentication) {
    DirContextOperations user = null;/*  w w w.  j  a  v a 2s . c  om*/
    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.cloudfoundry.identity.uaa.user.JdbcUaaUserDatabase.java

@Override
public UaaUser retrieveUserByName(String username, String origin) throws UsernameNotFoundException {
    try {/*from   w ww.ja  v  a  2s  .com*/
        String sql = isCaseInsensitive() ? DEFAULT_CASE_INSENSITIVE_USER_BY_USERNAME_QUERY
                : DEFAULT_CASE_SENSITIVE_USER_BY_USERNAME_QUERY;
        return jdbcTemplate.queryForObject(sql, mapper, username.toLowerCase(Locale.US), true, origin,
                IdentityZoneHolder.get().getId());
    } catch (EmptyResultDataAccessException e) {
        throw new UsernameNotFoundException(username);
    }
}

From source file:org.cloudfoundry.identity.uaa.user.JdbcUaaUserDatabase.java

@Override
public UaaUser retrieveUserById(String id) throws UsernameNotFoundException {
    try {//from   w  w  w. j  a  v a2 s  . c  o m
        return jdbcTemplate.queryForObject(DEFAULT_USER_BY_ID_QUERY, mapper, id, true,
                IdentityZoneHolder.get().getId());
    } catch (EmptyResultDataAccessException e) {
        throw new UsernameNotFoundException(id);
    }
}

From source file:org.codelabor.system.userdetails.services.UserDetailsServiceImpl.java

@SuppressWarnings("unchecked")
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
    String queryId = null;//from w ww  . j av a2  s.com
    UserDetails userDetails = null;
    try {
        // get username, password
        queryId = "system.userdetails.select.users.by.username";
        Collection userMapCollection = queryService.find(queryId, new Object[] { username });
        if (userMapCollection.size() == 0) {
            throw new UsernameNotFoundException(queryId);
        }
        Map userMap = (Map) userMapCollection.toArray()[0];
        String password = (String) userMap.get("password");
        boolean enabled = ((BigDecimal) userMap.get("enabled")).intValue() == 1 ? true : false;

        // get authorities
        queryId = "system.userdetails.select.authorities.by.username";
        Collection authorityCollection = queryService.find(queryId, new Object[] { username });
        Iterator authorityIterator = authorityCollection.iterator();
        List authorityList = new ArrayList();
        while (authorityIterator.hasNext()) {
            Map authorityMap = (Map) authorityIterator.next();
            if (log.isDebugEnabled()) {
                StringBuilder sb = new StringBuilder();
                sb.append("authorityMap: ").append(authorityMap);
                log.debug(sb.toString());
            }
            GrantedAuthority authority = new GrantedAuthorityImpl((String) authorityMap.get("authority"));
            authorityList.add(authority);
        }

        // create user details
        userDetails = new User(username, password, enabled, true, true, true, authorityList);
    } catch (QueryServiceException e) {
        e.printStackTrace();
        throw new UnkownQueryServiceException(e.getMessage());
    }
    return userDetails;
}

From source file:org.codenergic.theskeleton.user.impl.UserServiceImpl.java

private Supplier<UsernameNotFoundException> throwUsernameNotFound(String username) {
    return () -> new UsernameNotFoundException(username);
}