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:net.seedboxer.web.security.SeedBoxerUDS.java

public UserDetails loadUserByAPIKey(String apikey) throws UsernameNotFoundException {
    try {/*from  ww w  .j a  va2s  . c o m*/
        User u = userController.getUserFromAPIKey(apikey);
        return new SeedBoxerUserDetails(u);
    } catch (IllegalArgumentException e) {
        throw new UsernameNotFoundException("User with APIKey '" + apikey + "' not found", e);
    }
}

From source file:com.po.service.UserDetailsServiceImpl.java

/**
  * Locates the user based on the username.
  */*w w  w. j  a v a 2 s.c om*/
  * @param username string the username
  * @return the user details
  */
@Override
public final UserDetails loadUserByUsername(final String username) {
    Objectify ofy = objectifyFactory.begin();
    final List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    Account user = (Account) memcacheService.get(username);

    if (user == null) {
        try {
            user = ofy.get(Account.class, username);
            memcacheService.put(username, user, Expiration.byDeltaSeconds(DEFAULT_EXPIRATION));
        } catch (NotFoundException e) {
            throw new UsernameNotFoundException("Username not found.", e);
        }
    }

    authorities.add(new GrantedAuthorityImpl("ROLE_USER"));
    return new EnhancedUser(user.getUserName(), user.getEmail(), user.getFirstName() + " " + user.getLastName(),
            user.getPassword(), "", true, true, true, true, authorities);
}

From source file:whitelabel.cloud.webapp.security.spring.CloudUserDetailsAuthenticationProvider.java

@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
        throws AuthenticationException {

    CloudWebAutenticationDetails details = ((CloudWebAutenticationDetails) authentication.getDetails());

    WsEndUserClient wsEndUser = new WsEndUserClient(wsEndUserNamespace, wsEndUserServiceName,
            details.getDatacenterUrl() + wsEndUserEndpoint);
    AppUserToken utoken = null;//from ww  w  .j av  a 2 s. c o  m
    try {
        utoken = wsEndUser.loginAs(username, authentication.getCredentials().toString());
    } catch (Exception e) {
        throw new UsernameNotFoundException("USERNAME_NOT_FOUND", e);
    }

    if (utoken == null || !utoken.isValid()) {
        throw new UsernameNotFoundException("USERNAME_NOT_FOUND");
    }
    // create new cloud-user
    CloudUser cu = new CloudUser(username, authentication.getCredentials().toString(),
            details.getDatacenterId());
    // set di wsEndUser to the user (so every ws-invoke use same authentication token)
    cu.setWsEndUser(wsEndUser);

    try {
        //find VDCResourceConfiguration
        WsEndUserVDCConfigClient wsEndUserVDCConfigClient = new WsEndUserVDCConfigClient(wsEndUserNamespace,
                wsEndUserServiceName, details.getDatacenterUrl() + wsEndUserEndpoint);
        wsEndUserVDCConfigClient.setCredentials(utoken.getUserName(), utoken.getToken());
        cu.setVdcResourceBoundConfig(wsEndUserVDCConfigClient.getVDCResourceConfiguration());
    } catch (Exception e) {
        throw new UsernameNotFoundException("VDC_CONFIG_NOT_FOUND", e);
    }

    return new UserDetailsImpl(cu);

}

From source file:org.syncope.core.security.SyncopeAuthenticationProvider.java

@Override
@Transactional(noRollbackFor = { BadCredentialsException.class })
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {

    boolean authenticated;
    SyncopeUser passwordUser = new SyncopeUser();
    SyncopeUser user = null;/*w w  w  .  j  av a 2 s.c om*/

    if (adminUser.equals(authentication.getPrincipal())) {
        passwordUser.setPassword(authentication.getCredentials().toString(), CipherAlgorithm.MD5, 0);

        authenticated = adminMD5Password.equalsIgnoreCase(passwordUser.getPassword());
    } else {
        String username;
        try {
            username = authentication.getPrincipal().toString();
        } catch (NumberFormatException e) {
            throw new UsernameNotFoundException("Invalid username: " + authentication.getName(), e);
        }

        user = userDAO.find(username);
        if (user == null) {
            throw new UsernameNotFoundException("Could not find user " + username);
        }

        passwordUser.setPassword(authentication.getCredentials().toString(), user.getCipherAlgoritm(), 0);

        authenticated = user.getPassword().equalsIgnoreCase(passwordUser.getPassword());
    }

    Authentication result;

    if ((user == null || !user.getSuspended()) && authenticated) {
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                authentication.getPrincipal(), null, userDetailsService
                        .loadUserByUsername(authentication.getPrincipal().toString()).getAuthorities());
        token.setDetails(authentication.getDetails());

        result = token;

        LOG.debug("User {} authenticated with roles {}", authentication.getPrincipal(), token.getAuthorities());

        if (user != null) {
            user.setLastLoginDate(new Date());
            user.setFailedLogins(0);
            userDAO.save(user);
        }

    } else {
        result = authentication;

        if (user != null && !user.getSuspended()) {
            user.setFailedLogins(user.getFailedLogins() + 1);
            userDAO.save(user);
        }

        LOG.debug("User {} not authenticated", authentication.getPrincipal());

        throw new BadCredentialsException("User " + authentication.getPrincipal() + " not authenticated");
    }

    return result;
}

From source file:fr.xebia.springframework.security.core.userdetails.jdbc.ExtendedJdbcUserDetailsManager.java

@Override
protected UserDetails createUserDetails(String username, UserDetails userFromUserQuery,
        List<GrantedAuthority> combinedAuthorities) {
    final User user = (User) super.createUserDetails(username, userFromUserQuery, combinedAuthorities);
    List<UserDetails> users = getJdbcTemplate().query(selectUserExtraColumns, new String[] { username },
            new RowMapper<UserDetails>() {
                public UserDetails mapRow(ResultSet rs, int rowNum) throws SQLException {
                    ExtendedUser extendedUser = new ExtendedUser(user.getUsername(), user.getPassword(),
                            user.isEnabled(), user.isAccountNonExpired(), user.isCredentialsNonExpired(),
                            user.isAccountNonLocked(), user.getAuthorities());
                    extendedUser.setAllowedRemoteAddresses(rs.getString(1));
                    extendedUser.setComments(rs.getString(2));

                    return extendedUser;
                }/*from w w  w  .ja v  a2s .com*/
            });
    if (users.size() == 0) {
        throw new UsernameNotFoundException(messages.getMessage("JdbcDaoImpl.notFound",
                new Object[] { username }, "Username {0} not found"), username);
    }
    return users.get(0);
}

From source file:io.gravitee.management.idp.repository.authentication.RepositoryAuthenticationProvider.java

@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
        throws AuthenticationException {
    try {//from   www. j  a  va  2 s . com
        UserEntity user = userService.findByName(username);
        return mapUserEntityToUserDetails(user);
    } catch (UserNotFoundException notFound) {
        throw new UsernameNotFoundException("User '" + username + "' not found", notFound);
    } catch (Exception repositoryProblem) {
        LOGGER.error("Failed to retrieveUser : {}", username, repositoryProblem);
        throw new InternalAuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem);
    }
}

From source file:org.itracker.services.implementations.UserServiceImpl.java

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    try {/*from   ww  w  .  j a v a2  s.c  o  m*/
        final User model = getUserByLogin(username);
        return new ITrackerUserDetails(model, getPermissionsByUserId(model.getId()));
    } catch (NoSuchEntityException e) {
        throw new UsernameNotFoundException(username, e);
    }
}

From source file:com.assetmanager.service.auth.UserDetailsServiceImpl.java

/**
 * Locates the user based on the username.
 *
 * @param username string the username/*  w  w w .  j  a  v  a  2  s.c o  m*/
 * @return the user details
 */
@Override
public final UserDetails loadUserByUsername(final String username) {
    final List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    UserAccount user = (UserAccount) memcacheService.get(username);

    if (user == null) {
        final Query query = entityManager.createQuery("SELECT u FROM UserAccount u WHERE username = :username");
        query.setParameter(USERNAME, username);

        try {
            user = (UserAccount) query.getSingleResult();

            memcacheService.put(username, user, Expiration.byDeltaSeconds(DEFAULT_EXPIRATION));
        } catch (NoResultException e) {
            throw new UsernameNotFoundException("Username not found.", e);
        }
    }

    authorities.add(new SimpleGrantedAuthority(user.getRole()));

    return new EnhancedUser(user.getUsername(), user.getEmail(), user.getDisplayName(), user.getPassword(),
            user.getSalt(), user.isEnabled(), user.isAccountNonExpired(), user.isCredentialsNonExpired(),
            user.isAccountNonLocked(), authorities);
}

From source file:com.assetmanager.service.auth.UserDetailsServiceImpl.java

/**
 * Indicates if the activation e-mail has been sent.
 *
 * @param username the username/* ww  w .  j  a  va  2s. c  om*/
 * @return true if sent; false otherwise
 */
@Override
public final boolean isActivationEmailSent(final String username) {
    UserAccount user = (UserAccount) memcacheService.get(username);

    if (user == null) {
        final Query query = entityManager.createQuery(SELECT_USER);
        query.setParameter(USERNAME, username);

        try {
            user = (UserAccount) query.getSingleResult();

            memcacheService.put(username, user, Expiration.byDeltaSeconds(DEFAULT_EXPIRATION));
        } catch (NoResultException e) {
            throw new UsernameNotFoundException("Username not found.", e);
        }
    }

    return user.isActivationEmailSent();
}

From source file:com.assetmanager.service.auth.UserDetailsServiceImpl.java

/**
 * Updates the activation e-mail sent status.
 *
 * @param username the username/*  w w  w  .  j  a v  a 2s . c  o m*/
 */
@Override
@Transactional
public final void activationEmailSent(final String username) {
    final Query query = entityManager.createQuery(SELECT_USER);
    query.setParameter(USERNAME, username);

    try {
        final UserAccount user = (UserAccount) query.getSingleResult();
        user.setActivationEmailSent(true);

        entityManager.persist(user);

        memcacheService.put(user.getUsername(), user, Expiration.byDeltaSeconds(DEFAULT_EXPIRATION));
    } catch (NoResultException e) {
        throw new UsernameNotFoundException("Username not found.", e);
    }
}