Search in sources :

Example 56 with UsernameNotFoundException

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

the class PasswordComparisonAuthenticator method authenticate.

@Override
public DirContextOperations authenticate(final Authentication authentication) {
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, "Can only process UsernamePasswordAuthenticationToken objects");
    // locate the user and check the password
    DirContextOperations user = null;
    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) {
            logger.trace(LogMessage.format("Failed to retrieve user with %s", userDn), ignore);
        }
        if (user != null) {
            break;
        }
    }
    if (user == null) {
        logger.debug(LogMessage.of(() -> "Failed to retrieve user with any user DNs " + getUserDns(username)));
    }
    if (user == null && getUserSearch() != null) {
        logger.trace("Searching for user using " + getUserSearch());
        user = getUserSearch().searchForUser(username);
        if (user == null) {
            logger.debug("Failed to find user using " + getUserSearch());
        }
    }
    if (user == null) {
        throw new UsernameNotFoundException("User not found: " + username);
    }
    if (logger.isTraceEnabled()) {
        logger.trace(LogMessage.format("Comparing password attribute '%s' for user '%s'", this.passwordAttributeName, user.getDn()));
    }
    if (this.usePasswordAttrCompare && isPasswordAttrCompare(user, password)) {
        logger.debug(LogMessage.format("Locally matched password attribute '%s' for user '%s'", this.passwordAttributeName, user.getDn()));
        return user;
    }
    if (isLdapPasswordCompare(user, ldapTemplate, password)) {
        logger.debug(LogMessage.format("LDAP-matched password attribute '%s' for user '%s'", this.passwordAttributeName, user.getDn()));
        return user;
    }
    throw new BadCredentialsException(this.messages.getMessage("PasswordComparisonAuthenticator.badCredentials", "Bad credentials"));
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) SpringSecurityLdapTemplate(org.springframework.security.ldap.SpringSecurityLdapTemplate) DirContextOperations(org.springframework.ldap.core.DirContextOperations) NameNotFoundException(org.springframework.ldap.NameNotFoundException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 57 with UsernameNotFoundException

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

the class DefaultAuthenticationEventPublisherTests method expectedDefaultMappingsAreSatisfied.

@Test
public void expectedDefaultMappingsAreSatisfied() {
    this.publisher = new DefaultAuthenticationEventPublisher();
    ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
    this.publisher.setApplicationEventPublisher(appPublisher);
    Authentication a = mock(Authentication.class);
    Exception cause = new Exception();
    Object extraInfo = new Object();
    this.publisher.publishAuthenticationFailure(new BadCredentialsException(""), a);
    this.publisher.publishAuthenticationFailure(new BadCredentialsException("", cause), a);
    verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureBadCredentialsEvent.class));
    reset(appPublisher);
    this.publisher.publishAuthenticationFailure(new UsernameNotFoundException(""), a);
    this.publisher.publishAuthenticationFailure(new UsernameNotFoundException("", cause), a);
    this.publisher.publishAuthenticationFailure(new AccountExpiredException(""), a);
    this.publisher.publishAuthenticationFailure(new AccountExpiredException("", cause), a);
    this.publisher.publishAuthenticationFailure(new ProviderNotFoundException(""), a);
    this.publisher.publishAuthenticationFailure(new DisabledException(""), a);
    this.publisher.publishAuthenticationFailure(new DisabledException("", cause), a);
    this.publisher.publishAuthenticationFailure(new LockedException(""), a);
    this.publisher.publishAuthenticationFailure(new LockedException("", cause), a);
    this.publisher.publishAuthenticationFailure(new AuthenticationServiceException(""), a);
    this.publisher.publishAuthenticationFailure(new AuthenticationServiceException("", cause), a);
    this.publisher.publishAuthenticationFailure(new CredentialsExpiredException(""), a);
    this.publisher.publishAuthenticationFailure(new CredentialsExpiredException("", cause), a);
    verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureBadCredentialsEvent.class));
    verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureExpiredEvent.class));
    verify(appPublisher).publishEvent(isA(AuthenticationFailureProviderNotFoundEvent.class));
    verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureDisabledEvent.class));
    verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureLockedEvent.class));
    verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureServiceExceptionEvent.class));
    verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureCredentialsExpiredEvent.class));
    verifyNoMoreInteractions(appPublisher);
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) AuthenticationFailureProviderNotFoundEvent(org.springframework.security.authentication.event.AuthenticationFailureProviderNotFoundEvent) AuthenticationFailureBadCredentialsEvent(org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) AuthenticationException(org.springframework.security.core.AuthenticationException) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) AuthenticationFailureServiceExceptionEvent(org.springframework.security.authentication.event.AuthenticationFailureServiceExceptionEvent) AuthenticationFailureLockedEvent(org.springframework.security.authentication.event.AuthenticationFailureLockedEvent) Authentication(org.springframework.security.core.Authentication) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) AuthenticationFailureCredentialsExpiredEvent(org.springframework.security.authentication.event.AuthenticationFailureCredentialsExpiredEvent) AuthenticationFailureDisabledEvent(org.springframework.security.authentication.event.AuthenticationFailureDisabledEvent) AuthenticationFailureExpiredEvent(org.springframework.security.authentication.event.AuthenticationFailureExpiredEvent) Test(org.junit.jupiter.api.Test)

Example 58 with UsernameNotFoundException

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

the class DigestAuthenticationFilter method doFilter.

private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
    String header = request.getHeader("Authorization");
    if (header == null || !header.startsWith("Digest ")) {
        chain.doFilter(request, response);
        return;
    }
    logger.debug(LogMessage.format("Digest Authorization header received from user agent: %s", header));
    DigestData digestAuth = new DigestData(header);
    try {
        digestAuth.validateAndDecode(this.authenticationEntryPoint.getKey(), this.authenticationEntryPoint.getRealmName());
    } catch (BadCredentialsException ex) {
        fail(request, response, ex);
        return;
    }
    // Lookup password for presented username. N.B. DAO-provided password MUST be
    // clear text - not encoded/salted (unless this instance's passwordAlreadyEncoded
    // property is 'false')
    boolean cacheWasUsed = true;
    UserDetails user = this.userCache.getUserFromCache(digestAuth.getUsername());
    String serverDigestMd5;
    try {
        if (user == null) {
            cacheWasUsed = false;
            user = this.userDetailsService.loadUserByUsername(digestAuth.getUsername());
            if (user == null) {
                throw new AuthenticationServiceException("AuthenticationDao returned null, which is an interface contract violation");
            }
            this.userCache.putUserInCache(user);
        }
        serverDigestMd5 = digestAuth.calculateServerDigest(user.getPassword(), request.getMethod());
        // If digest is incorrect, try refreshing from backend and recomputing
        if (!serverDigestMd5.equals(digestAuth.getResponse()) && cacheWasUsed) {
            logger.debug("Digest comparison failure; trying to refresh user from DAO in case password had changed");
            user = this.userDetailsService.loadUserByUsername(digestAuth.getUsername());
            this.userCache.putUserInCache(user);
            serverDigestMd5 = digestAuth.calculateServerDigest(user.getPassword(), request.getMethod());
        }
    } catch (UsernameNotFoundException ex) {
        String message = this.messages.getMessage("DigestAuthenticationFilter.usernameNotFound", new Object[] { digestAuth.getUsername() }, "Username {0} not found");
        fail(request, response, new BadCredentialsException(message));
        return;
    }
    // If digest is still incorrect, definitely reject authentication attempt
    if (!serverDigestMd5.equals(digestAuth.getResponse())) {
        logger.debug(LogMessage.format("Expected response: '%s' but received: '%s'; is AuthenticationDao returning clear text passwords?", serverDigestMd5, digestAuth.getResponse()));
        String message = this.messages.getMessage("DigestAuthenticationFilter.incorrectResponse", "Incorrect response");
        fail(request, response, new BadCredentialsException(message));
        return;
    }
    // but the request was otherwise appearing to be valid
    if (digestAuth.isNonceExpired()) {
        String message = this.messages.getMessage("DigestAuthenticationFilter.nonceExpired", "Nonce has expired/timed out");
        fail(request, response, new NonceExpiredException(message));
        return;
    }
    logger.debug(LogMessage.format("Authentication success for user: '%s' with response: '%s'", digestAuth.getUsername(), digestAuth.getResponse()));
    Authentication authentication = createSuccessfulAuthentication(request, user);
    SecurityContext context = SecurityContextHolder.createEmptyContext();
    context.setAuthentication(authentication);
    SecurityContextHolder.setContext(context);
    chain.doFilter(request, response);
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) UserDetails(org.springframework.security.core.userdetails.UserDetails) Authentication(org.springframework.security.core.Authentication) SecurityContext(org.springframework.security.core.context.SecurityContext) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException)

Example 59 with UsernameNotFoundException

use of org.springframework.security.core.userdetails.UsernameNotFoundException in project google-app-engine-jappstart by taylorleese.

the class UserDetailsServiceImpl method loadUserByUsername.

/**
 * Locates the user based on the username.
 *
 * @param username string the username
 * @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);
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) Query(javax.persistence.Query) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) ArrayList(java.util.ArrayList) NoResultException(javax.persistence.NoResultException) UserAccount(com.jappstart.model.auth.UserAccount)

Example 60 with UsernameNotFoundException

use of org.springframework.security.core.userdetails.UsernameNotFoundException in project google-app-engine-jappstart by taylorleese.

the class UserDetailsServiceImpl method activationEmailSent.

/**
 * Updates the activation e-mail sent status.
 *
 * @param username the username
 */
@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);
    }
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) Query(javax.persistence.Query) NoResultException(javax.persistence.NoResultException) UserAccount(com.jappstart.model.auth.UserAccount) Transactional(org.springframework.transaction.annotation.Transactional)

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