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:com.devnexus.ting.core.service.impl.UserServiceImpl.java

/**
 * {@inheritDoc}/*from  w  w  w . j a v a2 s .c o  m*/
 */
@Override
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public UserDetails loadUserByUsername(final String userName)
        throws UsernameNotFoundException, DataAccessException {

    final User user = userDao.getUserByUsername(userName.trim());

    if (user == null) {
        LOGGER.warn("loadUserByUsername() - No user with id " + userName + " found.");
        throw new UsernameNotFoundException("loadUserByUsername() - No user with id " + userName + " found.");
    }

    LOGGER.info("User {} ({}) loaded.", new Object[] { user.getUsername(), user.getEmail() });

    return user;
}

From source file:gr.abiss.calipso.userDetails.service.impl.UserDetailsServiceImpl.java

/**
 * {@inheritDoc}//w w  w. ja v  a  2 s. c  om
 * 
 * @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
 */
@Override
public ICalipsoUserDetails loadUserByUsername(String findByUsernameOrEmail) throws UsernameNotFoundException {
    ICalipsoUserDetails userDetails = null;

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("loadUserByUsername using: " + findByUsernameOrEmail);
    }
    LocalUser user = this.localUserService.findByUserNameOrEmail(findByUsernameOrEmail);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("loadUserByUsername user: " + user);
    }

    userDetails = UserDetails.fromUser(user);
    userDetails.setNotificationCount(this.baseNotificationService.countUnseen(userDetails));

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("loadUserByUsername returns userDetails: " + userDetails + ",    with roles: "
                + userDetails.getAuthorities());
    }
    if (user == null) {
        throw new UsernameNotFoundException("Could not match username: " + findByUsernameOrEmail);
    }

    return userDetails;
}

From source file:org.cloudfoundry.identity.uaa.authentication.manager.LoginAuthenticationManagerTests.java

@Test(expected = BadCredentialsException.class)
public void testFailedAutoAddButWithNewUser() {
    manager.setAddNewAccounts(true);/*from w  w w. j ava  2  s  .  c om*/
    UaaUser user = UaaUserTestFactory.getUser("FOO", "foo", "fo@test.org", "Foo", "Bar");
    Mockito.when(userDatabase.retrieveUserByName("foo")).thenThrow(new UsernameNotFoundException("planned"));
    Authentication authentication = manager
            .authenticate(UaaAuthenticationTestFactory.getAuthenticationRequest("foo"));
    assertEquals(user.getUsername(), ((UaaPrincipal) authentication.getPrincipal()).getName());
    assertEquals(user.getId(), ((UaaPrincipal) authentication.getPrincipal()).getId());
}

From source file:org.opendatakit.security.spring.UserDetailsServiceImpl.java

@Override
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException, DataAccessException {
    if (name == null) {
        throw new IllegalStateException("Username cannot be null");
    }//from  www .  j ava  2  s .  co m

    User user = userService.getDaemonAccountUser();

    final String uriUser;
    final String password;
    final String salt;
    final Set<GrantedAuthority> grantedAuthorities;
    final boolean isEnabled = true;
    final boolean isCredentialNonExpired = true;
    try {
        if (credentialType == CredentialType.Username) {
            RegisteredUsersTable registeredUsersTable;
            // first call from digest, basic or forms-based auth
            if (name.startsWith(RegisteredUsersTable.UID_PREFIX)) {
                registeredUsersTable = RegisteredUsersTable.getUserByUri(name, datastore, user);
                if (registeredUsersTable == null) {
                    throw new UsernameNotFoundException("UID " + name + " is not recognized.");
                }
            } else {
                registeredUsersTable = RegisteredUsersTable.getUniqueUserByUsername(name, datastore, user);
                if (registeredUsersTable == null) {
                    throw new UsernameNotFoundException(
                            "User " + name + " is not registered or the registered users table is corrupt.");
                }
            }
            uriUser = registeredUsersTable.getUri();

            // Along with BasicUsingDigest* classes, we allow both types of authentication to use the
            // same DB field for password.
            switch (passwordType) {
            case BasicAuth:
                // password = registeredUsersTable.getBasicAuthPassword();
                // salt = registeredUsersTable.getBasicAuthSalt();
                // break;
            case DigestAuth:
                password = registeredUsersTable.getDigestAuthPassword();
                salt = UUID.randomUUID().toString();
                break;
            default:
                throw new AuthenticationCredentialsNotFoundException(
                        "Password type " + passwordType.toString() + " cannot be interpretted");
            }

            grantedAuthorities = getGrantedAuthorities(registeredUsersTable.getUri());
            if (password == null) {
                throw new AuthenticationCredentialsNotFoundException("User " + name
                        + " does not have a password configured. You must close and re-open your browser to clear this error.");
            }
        } else {
            // OAuth2 token...
            // there is no password for an OAuth2 credential
            if (passwordType != PasswordType.Random) {
                throw new AuthenticationCredentialsNotFoundException(
                        "Password type " + passwordType.toString() + " cannot be interpretted");
            }
            // set password and salt to unguessable strings...
            password = UUID.randomUUID().toString();
            salt = UUID.randomUUID().toString();

            // try to find user in registered users table...
            RegisteredUsersTable eUser = RegisteredUsersTable.getUniqueUserByEmail(name, datastore, user);
            if (eUser != null) {
                uriUser = eUser.getUri();
                grantedAuthorities = getGrantedAuthorities(eUser.getUri());
            } else {
                throw new UsernameNotFoundException("User " + name + " is not registered");
            }
        }
    } catch (ODKDatastoreException e) {
        throw new TransientDataAccessResourceException("persistence layer problem", e);
    }

    return new OdkServerUser(uriUser, password, salt, "-undefined-", isEnabled, true, isCredentialNonExpired,
            true, grantedAuthorities);
}

From source file:ph.fingra.statisticsweb.security.FingraphAnthenticationProvider.java

@SuppressWarnings("unused")
@Override/*from w w  w.  ja v  a 2s . co m*/
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
        throws AuthenticationException {

    // admin.properties values
    logger.debug("[adminEmail] {}", adminEmail);
    logger.debug("[adminName] {}", adminName);
    logger.debug("[adminPassword] {}", adminPassword);

    UserDetails loadedUser = null;
    try {
        logger.debug("retrieveUser {}", username);

        Member member = null;
        if (username.equals(adminEmail)) {
            member = new Member();
            member.setEmail(adminEmail);
            member.setName(adminName);
            member.setPassword(adminPassword);
            member.setStatus(MemberStatus.ACTIVE.getValue());
            member.setJoinstatus(MemberJoinstatus.APPROVAL.getValue());
            member.setRole(MemberRole.ROLE_ADMIN.getValue());
        } else {
            member = memberService.get(username);
        }
        if (member == null) {
            throw new UsernameNotFoundException("Not found user id");
        }

        // lastlogin update
        if (member.getRole() == MemberRole.ROLE_USER.getValue()) {
            memberService.updateMemberLastLoginTime(member);
        }

        if (member.getRole() == MemberRole.ROLE_ADMIN.getValue()) {
            //logger.debug("passwordEncoder {}", adminPasswordEncoder);
            loadedUser = new FingraphUser(member, adminPasswordEncoder);
        } else {
            loadedUser = new FingraphUser(member);
        }
        logger.debug("userDetail is {}", loadedUser.toString());
    } catch (UsernameNotFoundException notFound) {
        if (authentication.getCredentials() != null) {
            String presentedPassword = authentication.getCredentials().toString();
            passwordEncoder.isPasswordValid(userNotFoundEncodedPassword, presentedPassword, null);
        }
        throw notFound;
    } catch (Exception repositoryProblem) {
        throw new AuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem);
    }

    if (loadedUser == null) {
        throw new AuthenticationServiceException(
                "UserDetailsService returned null, which is an interface contract violation");
    }

    return loadedUser;
}

From source file:org.jasig.cas.userdetails.LdapUserDetailsService.java

@Override
public UserDetails loadUserByUsername(final String username) {
    final SearchResult userResult;
    try {//from  w  ww.j a v  a2  s.c om
        logger.debug("Attempting to get details for user {}.", username);
        final Response<SearchResult> response = this.userSearchExecutor.search(this.connectionFactory,
                createSearchFilter(this.userSearchExecutor, username));
        logger.debug("LDAP user search response: {}", response);
        userResult = response.getResult();
    } catch (final LdapException e) {
        throw new RuntimeException("LDAP error fetching details for user.", e);
    }
    if (userResult.size() == 0) {
        throw new UsernameNotFoundException(username + " not found.");
    }
    if (userResult.size() > 1 && !this.allowMultipleResults) {
        throw new IllegalStateException(
                "Found multiple results for user which is not allowed (allowMultipleResults=false).");
    }
    final LdapEntry userResultEntry = userResult.getEntry();
    final String userDn = userResultEntry.getDn();
    final LdapAttribute userAttribute = userResultEntry.getAttribute(this.userAttributeName);
    if (userAttribute == null) {
        throw new IllegalStateException(this.userAttributeName + " attribute not found in results.");
    }
    final String id = userAttribute.getStringValue();

    final SearchResult roleResult;
    try {
        logger.debug("Attempting to get roles for user {}.", userDn);
        final Response<SearchResult> response = this.roleSearchExecutor.search(this.connectionFactory,
                createSearchFilter(this.roleSearchExecutor, userDn));
        logger.debug("LDAP role search response: {}", response);
        roleResult = response.getResult();
    } catch (final LdapException e) {
        throw new RuntimeException("LDAP error fetching roles for user.", e);
    }
    LdapAttribute roleAttribute;
    final Collection<SimpleGrantedAuthority> roles = new ArrayList<>(roleResult.size());
    for (final LdapEntry entry : roleResult.getEntries()) {
        roleAttribute = entry.getAttribute(this.roleAttributeName);
        if (roleAttribute == null) {
            logger.warn("Role attribute not found on entry {}", entry);
            continue;
        }

        for (final String role : roleAttribute.getStringValues()) {
            roles.add(new SimpleGrantedAuthority(this.rolePrefix + role.toUpperCase()));
        }

    }

    return new User(id, UNKNOWN_PASSWORD, roles);
}

From source file:com.github.jens_meiss.blog.web.user.UserController.java

@Override
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {

    logger.debug("loadUserByUsername");

    final UserDetailsDTO userDetailsDTO = userService.findByUserName(username);
    if (userDetailsDTO == null)
        throw new UsernameNotFoundException("Username Not Found");

    final List<SimpleGrantedAuthority> roles = new LinkedList<SimpleGrantedAuthority>();
    roles.add(new SimpleGrantedAuthority("ROLE_USER"));

    return new User(userDetailsDTO.getUserName(), userDetailsDTO.getPassword(), true, true, true, true, roles);

}

From source file:gr.abiss.calipso.service.impl.UserServiceImpl.java

@Override
@Transactional(readOnly = false)/*from   w  ww  .ja va  2  s .c o m*/
public User handlePasswordResetToken(String userNameOrEmail, String token, String newPassword) {
    Assert.notNull(userNameOrEmail);
    User user = this.findByUserNameOrEmail(userNameOrEmail);
    if (user == null) {
        throw new UsernameNotFoundException("Could not match username: " + userNameOrEmail);
    }
    user.setResetPasswordToken(null);
    user.setPassword(newPassword);
    user = this.update(user);

    LOGGER.info("handlePasswordResetToken returning local user: " + user);
    return user;
}

From source file:com.abixen.platform.core.service.impl.UserServiceImpl.java

@Override
public UserChangePasswordForm changeUserPassword(User user, UserChangePasswordForm userChangePasswordForm) {
    log.info("changeUserPassword()");

    PasswordEncoder encoder = new BCryptPasswordEncoder();
    String password = userChangePasswordForm.getCurrentPassword();
    if (!encoder.matches(password, user.getPassword())) {
        throw new UsernameNotFoundException("Wrong username and / or password.");
    }/*w  ww.  ja  v a2 s. c o m*/

    user.setPassword(encoder.encode(userChangePasswordForm.getNewPassword()));
    updateUser(user);

    return userChangePasswordForm;
}

From source file:edu.vt.middleware.cas.userdetails.LdapUserDetailsService.java

@Override
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
    final SearchResult userResult;
    try {//  ww  w. j a v a  2  s  .  c  o m
        logger.debug("Attempting to get details for user {}.", username);
        final Response<SearchResult> response = userSearchExecutor.search(connectionFactory,
                filterWithParams(userSearchExecutor, username));
        logger.debug("LDAP user search response: {}", response);
        userResult = response.getResult();
    } catch (LdapException e) {
        throw new RuntimeException("LDAP error fetching details for user.", e);
    }
    if (userResult.size() == 0) {
        throw new UsernameNotFoundException(username + " not found.");
    }
    if (userResult.size() > 1 && !allowMultipleResults) {
        throw new IllegalStateException(
                "Found multiple results for user which is not allowed (allowMultipleResults=false).");
    }
    final String userDn = userResult.getEntry().getDn();
    final LdapAttribute userAttribute = userResult.getEntry().getAttribute(userAttributeName);
    if (userAttribute == null) {
        throw new IllegalStateException(userAttributeName + " attribute not found in results.");
    }
    final String id = userAttribute.getStringValue();

    final SearchResult roleResult;
    try {
        logger.debug("Attempting to get roles for user {}.", userDn);
        final Response<SearchResult> response = roleSearchExecutor.search(connectionFactory,
                filterWithParams(roleSearchExecutor, userDn));
        logger.debug("LDAP role search response: {}", response);
        roleResult = response.getResult();
    } catch (LdapException e) {
        throw new RuntimeException("LDAP error fetching roles for user.", e);
    }
    LdapAttribute roleAttribute;
    final Collection<SimpleGrantedAuthority> roles = new ArrayList<SimpleGrantedAuthority>(roleResult.size());
    for (LdapEntry entry : roleResult.getEntries()) {
        roleAttribute = entry.getAttribute(roleAttributeName);
        if (roleAttribute == null) {
            logger.warn("Role attribute not found on entry {}", entry);
            continue;
        }
        roles.add(new SimpleGrantedAuthority(rolePrefix + roleAttribute.getStringValue().toUpperCase()));
    }

    return new User(id, UNKNOWN_PASSWORD, roles);
}