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.sharetask.service.UserServiceImpl.java

@Override
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
    final UserAuthentication user = userAuthenticationRepository.findByUsername(username);
    UserDetails userDetails = null;/*  www. j  a  v a  2 s .  c  om*/
    if (user != null) {
        userDetails = new UserDetailBuilder(user).build();
    } else {
        throw new UsernameNotFoundException("UserAuthentication with name: " + username + " not found");
    }
    return userDetails;
}

From source file:com.github.lynxdb.server.api.http.WebSecurityConfig.java

@Autowired
public void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(new AbstractUserDetailsAuthenticationProvider() {
        @Override//from   w w w.  j ava  2 s.co m
        protected void additionalAuthenticationChecks(UserDetails ud, UsernamePasswordAuthenticationToken upat)
                throws AuthenticationException {

        }

        @Override
        protected UserDetails retrieveUser(String string, UsernamePasswordAuthenticationToken upat)
                throws AuthenticationException {
            User user = users.byLogin(string);
            if (user == null) {
                throw new UsernameNotFoundException("No such User : " + string);
            }
            if (user.checkPassword(upat.getCredentials().toString())) {
                return user;
            } else {
                throw new BadCredentialsException("Bad credentials");

            }
        }
    });
}

From source file:eu.cloud4soa.frontend.commons.server.security.C4sAuthenticationProvider.java

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

    List<User> users = userRepository.findBy("username", username);
    if (users.isEmpty())
        throw new UsernameNotFoundException("User '" + username + "' not found.");

    User user = users.get(0);/* w w w.  j  av a  2s .c o  m*/

    Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
    if (C4sSubject.SUPER_USER.equals(username)) {
        authorities.addAll(AuthorityUtils.createAuthorityList(UserModel.USER_ROLES));
    } else if ("developer".equals(user.getUsertype().getName())) {
        authorities.addAll(AuthorityUtils.createAuthorityList(C4sSubject.USER_TYPE_DEVELOPER));
    } else if ("paasprovider".equals(user.getUsertype().getName())) {
        authorities.addAll(AuthorityUtils.createAuthorityList(C4sSubject.USER_TYPE_PROVIDER));
    }

    UserModel userModel = "developer".equals(user.getUsertype().getName())
            ? developerUserRepository.findByUriId(user.getUriID())
            : providerUserRepository.findByUriId(user.getUriID());

    if (userModel != null)
        for (String role : UserModel.USER_ROLES)
            if (Boolean.TRUE.equals(userModel.get(role)))
                authorities.addAll(AuthorityUtils.createAuthorityList(role));

    return new org.springframework.security.core.userdetails.User(username, user.getPassword(), authorities);

}

From source file:com.rockagen.gnext.service.spring.security.extension.ExAuthenticationProvider.java

/**
 * Create a new {@link org.springframework.security.core.userdetails.UserDetails} by uid
 *
 * @param uid         uid/*  w  ww  .jav  a2  s.c  o  m*/
 * @param credentials Credentials(always was password)
 * @return {@link org.springframework.security.core.userdetails.UserDetails}
 * @throws org.springframework.security.authentication.BadCredentialsException if credentials invalid
 */
private UserDetails loadUser(String uid, String credentials) {

    // Not empty
    if (CommUtil.isBlank(uid) || CommUtil.isBlank(credentials)) {
        throw new BadCredentialsException(messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }

    // Load user
    Optional<AuthUser> u = authUserServ.load(uid);

    if (u.filter(x -> x.enabled()).isPresent()) {
        AuthUser user = u.get();
        // Check credentials
        checkCredentials(user.getPassword(), credentials, user.getSalt());

        // After authenticated handler
        afterAuthenticatedHandler(user);

        List<GrantedAuthority> authorities = new LinkedList<>();
        Set<AuthGroup> groups = user.getGroups();
        if (groups != null && groups.size() > 0) {
            groups.forEach(x -> x.getRoles()
                    .forEach(y -> authorities.add(new SimpleGrantedAuthority(y.getName().trim()))));
        }
        return new User(user.getUid(), user.getPassword(), true, true, true, true, authorities);

    } else {
        throw new UsernameNotFoundException(
                messages.getMessage("", new Object[] { uid }, "User {0} has no GrantedAuthority"));
    }

}

From source file:ch.ge.ve.protopoc.config.WebSecurityAuthenticationConfigurer.java

@Bean
UserDetailsService userDetailsService() {
    return username -> {
        LOGGER.debug(String.format("Looking for user [%s]", username));
        Account account = accountRepository.findByUsername(username);
        if (account != null) {
            LOGGER.info(String.format("Found user [%s]", username));
            return new User(account.getUsername(), account.getPassword(), true, true, true, true,
                    AuthorityUtils.createAuthorityList("USER"));
        } else {/*ww w .  j  av a 2s  .com*/
            LOGGER.info(String.format("Couldn't find user [%s]", username));
            throw new UsernameNotFoundException(String.format("couldn't find the user '%s'", username));
        }
    };
}

From source file:net.navasoft.madcoin.backend.services.security.ProviderDataAccess.java

/**
 * Load user by username./*w w  w. j  a  v  a  2  s.  co  m*/
 * 
 * @param username
 *            the username
 * @return the user details
 * @throws UsernameNotFoundException
 *             the username not found exception
 * @throws DataAccessException
 *             the data access exception
 * @throws BadConfigException
 *             the bad config exception
 * @since 31/08/2014, 07:23:59 PM
 */
@Override
public UserDetails loadUserByUsername(String username)
        throws UsernameNotFoundException, DataAccessException, BadConfigException {
    String key = defineKey(username);
    if (initializer.containsKey(key)) {
        try {
            mapping.addValue("username", username, Types.VARCHAR);
            User user = dao.queryForObject(initializer.getProperty(key), mapping, defineMapper(username));
            return user;
        } catch (DataAccessException dao) {
            if (dao instanceof EmptyResultDataAccessException) {
                throw new UsernameNotFoundException(dao.getMessage());
            } else {
                dao.printStackTrace();
                throw dao;
            }
        }
    } else {
        throw new BadConfigException("Query is not defined.");
    }
}

From source file:com.miserablemind.butter.domain.model.user.user.impl.UserManagerImpl.java

@Override
@Transactional//from   w  ww.  ja  va  2  s  .c  om
public void changePassword(String password, AppUser user) throws UsernameNotFoundException {

    if (!user.isEnabled()) {
        throw new UsernameNotFoundException("Username Not Found");
    }

    String encodedPassword = this.passwordEncoder.encode(password);
    user.setPassword(encodedPassword);

    this.userDao.updateUser(user);
    this.userDao.deletePasswordResetTokensForUser(user.getId());
}

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

@Test(expected = BadCredentialsException.class)
public void testUserNotFoundNoAutoAdd() {
    Mockito.when(userDatabase.retrieveUserByName("foo")).thenThrow(new UsernameNotFoundException("planned"));
    manager.authenticate(UaaAuthenticationTestFactory.getAuthenticationRequest("foo"));
}

From source file:com.healthcit.analytics.dao.impl.UserDAO.java

public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
    List<User> userList = this.jdbcTemplate.query(
            messageSource.getMessage(SQL_GET_USER, null, Locale.getDefault()), new String[] { username },
            new UserRowMapper());
    if (userList.isEmpty()) {
        throw new UsernameNotFoundException("User with name '" + username + "' is not found. ");
    }//from w  w w . j av  a2s.com
    User user = userList.iterator().next();
    List<Role> roles = this.jdbcTemplate.query(
            messageSource.getMessage(SQL_GET_USER_ROLES, null, Locale.getDefault()),
            new Long[] { user.getId() }, new RoleRowMapper());
    user.getAuthorities().addAll(roles);
    return user;
}

From source file:com.sothawo.taboo2.Taboo2UserService.java

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    Optional<User> optionalUser;
    synchronized (knownUsers) {
        optionalUser = Optional.ofNullable(knownUsers.get(username));
        if (!optionalUser.isPresent()) {
            // reload the data from users file
            log.debug("loading user data");
            knownUsers.clear();//from  w w w .  j av a2s .c  o  m
            Optional.ofNullable(taboo2Configuration.getUsers()).ifPresent(filename -> {
                log.debug("user file: {}", filename);
                try {
                    Files.lines(Paths.get(filename)).map(String::trim).filter(line -> !line.isEmpty())
                            .filter(line -> !line.startsWith("#")).forEach(line -> {
                                String[] fields = line.split(":");
                                if (fields.length == 3) {
                                    String user = fields[0];
                                    String hashedPassword = fields[1];
                                    String[] roles = fields[2].split(",");
                                    if (roles.length < 1) {
                                        roles = new String[] { "undef" };
                                    }
                                    List<GrantedAuthority> authorities = new ArrayList<>();
                                    for (String role : roles) {
                                        authorities.add(new SimpleGrantedAuthority(role));
                                    }
                                    knownUsers.put(user, new User(user, hashedPassword, authorities));
                                }
                            });
                    log.debug("loaded {} user(s)", knownUsers.size());
                } catch (IOException e) {
                    log.debug("reading file", e);
                }
            });

            // search again after reload
            optionalUser = Optional.ofNullable(knownUsers.get(username));
        }
    }
    // need to return a copy as Spring security erases the password in the object after verification
    User user = optionalUser.orElseThrow(() -> new UsernameNotFoundException(username));
    return new User(user.getUsername(), user.getPassword(), user.getAuthorities());
}