Search in sources :

Example 51 with UsernameNotFoundException

use of org.springframework.security.core.userdetails.UsernameNotFoundException in project spring-security by spring-projects.

the class JdbcDaoImpl method loadUserByUsername.

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    List<UserDetails> users = loadUsersByUsername(username);
    if (users.size() == 0) {
        this.logger.debug("Query returned no results for user '" + username + "'");
        throw new UsernameNotFoundException(this.messages.getMessage("JdbcDaoImpl.notFound", new Object[] { username }, "Username {0} not found"));
    }
    // contains no GrantedAuthority[]
    UserDetails user = users.get(0);
    Set<GrantedAuthority> dbAuthsSet = new HashSet<>();
    if (this.enableAuthorities) {
        dbAuthsSet.addAll(loadUserAuthorities(user.getUsername()));
    }
    if (this.enableGroups) {
        dbAuthsSet.addAll(loadGroupAuthorities(user.getUsername()));
    }
    List<GrantedAuthority> dbAuths = new ArrayList<>(dbAuthsSet);
    addCustomAuthorities(user.getUsername(), dbAuths);
    if (dbAuths.size() == 0) {
        this.logger.debug("User '" + username + "' has no authorities and will be treated as 'not found'");
        throw new UsernameNotFoundException(this.messages.getMessage("JdbcDaoImpl.noAuthority", new Object[] { username }, "User {0} has no GrantedAuthority"));
    }
    return createUserDetails(username, user, dbAuths);
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) UserDetails(org.springframework.security.core.userdetails.UserDetails) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet)

Example 52 with UsernameNotFoundException

use of org.springframework.security.core.userdetails.UsernameNotFoundException in project spring-security by spring-projects.

the class ReactivePreAuthenticatedAuthenticationManager method authenticate.

@Override
public Mono<Authentication> authenticate(Authentication authentication) {
    return Mono.just(authentication).filter(this::supports).map(Authentication::getName).flatMap(this.userDetailsService::findByUsername).switchIfEmpty(Mono.error(() -> new UsernameNotFoundException("User not found"))).doOnNext(this.userDetailsChecker::check).map((userDetails) -> {
        PreAuthenticatedAuthenticationToken result = new PreAuthenticatedAuthenticationToken(userDetails, authentication.getCredentials(), userDetails.getAuthorities());
        result.setDetails(authentication.getDetails());
        return result;
    });
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) Authentication(org.springframework.security.core.Authentication) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken)

Example 53 with UsernameNotFoundException

use of org.springframework.security.core.userdetails.UsernameNotFoundException in project spring-security by spring-projects.

the class LdapAuthenticationProviderTests method usernameNotFoundExceptionIsHiddenByDefault.

@Test
public void usernameNotFoundExceptionIsHiddenByDefault() {
    final LdapAuthenticator authenticator = mock(LdapAuthenticator.class);
    final UsernamePasswordAuthenticationToken joe = new UsernamePasswordAuthenticationToken("joe", "password");
    given(authenticator.authenticate(joe)).willThrow(new UsernameNotFoundException("nobody"));
    LdapAuthenticationProvider provider = new LdapAuthenticationProvider(authenticator);
    assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(joe));
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) Test(org.junit.jupiter.api.Test)

Example 54 with UsernameNotFoundException

use of org.springframework.security.core.userdetails.UsernameNotFoundException in project spring-security by spring-projects.

the class FilterBasedLdapUserSearch method searchForUser.

/**
 * Return the LdapUserDetails containing the user's information
 * @param username the username to search for.
 * @return An LdapUserDetails object containing the details of the located user's
 * directory entry
 * @throws UsernameNotFoundException if no matching entry is found.
 */
@Override
public DirContextOperations searchForUser(String username) {
    logger.trace(LogMessage.of(() -> "Searching for user '" + username + "', with " + this));
    SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(this.contextSource);
    template.setSearchControls(this.searchControls);
    try {
        DirContextOperations operations = template.searchForSingleEntry(this.searchBase, this.searchFilter, new String[] { username });
        logger.debug(LogMessage.of(() -> "Found user '" + username + "', with " + this));
        return operations;
    } catch (IncorrectResultSizeDataAccessException ex) {
        if (ex.getActualSize() == 0) {
            throw new UsernameNotFoundException("User " + username + " not found in directory.");
        }
        // Search should never return multiple results if properly configured
        throw ex;
    }
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) SpringSecurityLdapTemplate(org.springframework.security.ldap.SpringSecurityLdapTemplate) DirContextOperations(org.springframework.ldap.core.DirContextOperations) IncorrectResultSizeDataAccessException(org.springframework.dao.IncorrectResultSizeDataAccessException)

Example 55 with UsernameNotFoundException

use of org.springframework.security.core.userdetails.UsernameNotFoundException in project spring-security by spring-projects.

the class ActiveDirectoryLdapAuthenticationProvider method searchForUser.

private DirContextOperations searchForUser(DirContext context, String username) throws NamingException {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    String bindPrincipal = createBindPrincipal(username);
    String searchRoot = (this.rootDn != null) ? this.rootDn : searchRootFromPrincipal(bindPrincipal);
    try {
        return SpringSecurityLdapTemplate.searchForSingleEntryInternal(context, searchControls, searchRoot, this.searchFilter, new Object[] { bindPrincipal, username });
    } catch (CommunicationException ex) {
        throw badLdapConnection(ex);
    } catch (IncorrectResultSizeDataAccessException ex) {
        // Search should never return multiple results if properly configured -
        if (ex.getActualSize() != 0) {
            throw ex;
        }
        // If we found no results, then the username/password did not match
        UsernameNotFoundException userNameNotFoundException = new UsernameNotFoundException("User " + username + " not found in directory.", ex);
        throw badCredentials(userNameNotFoundException);
    }
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) CommunicationException(org.springframework.ldap.CommunicationException) IncorrectResultSizeDataAccessException(org.springframework.dao.IncorrectResultSizeDataAccessException) SearchControls(javax.naming.directory.SearchControls)

Aggregations

UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)132 GrantedAuthority (org.springframework.security.core.GrantedAuthority)40 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)39 UserDetails (org.springframework.security.core.userdetails.UserDetails)36 Authentication (org.springframework.security.core.Authentication)24 Transactional (org.springframework.transaction.annotation.Transactional)20 Logger (org.slf4j.Logger)18 LoggerFactory (org.slf4j.LoggerFactory)18 java.util (java.util)16 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)15 Collectors (java.util.stream.Collectors)14 UserDetailsService (org.springframework.security.core.userdetails.UserDetailsService)14 Component (org.springframework.stereotype.Component)14 User (org.springframework.security.core.userdetails.User)13 ArrayList (java.util.ArrayList)12 HashSet (java.util.HashSet)11 UserRepository (io.github.jhipster.sample.repository.UserRepository)9 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)9 User (io.github.jhipster.sample.domain.User)6 Date (java.util.Date)6