Search in sources :

Example 6 with UsernameNotFoundException

use of org.springframework.security.core.userdetails.UsernameNotFoundException in project hale by halestudio.

the class UserDetailsServiceImpl method loadUserByUsername.

/**
 * @see UserDetailsService#loadUserByUsername(String)
 */
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    if (users == null) {
        update();
    }
    if (users.containsKey(username)) {
        String value = users.get(username);
        String[] parts = value.split(" ");
        if (parts == null || parts.length == 0 || parts[0] == null || parts[0].isEmpty()) {
            throw new UsernameNotFoundException("No password set for user");
        }
        // password
        String password = parts[0];
        // role
        String roleName = (parts.length > 1) ? (parts[1]) : (ROLE_USER);
        GrantedAuthority role = new SimpleGrantedAuthority(roleName);
        Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
        authorities.add(role);
        return new User(username, password, true, true, true, true, authorities);
    } else {
        throw new UsernameNotFoundException("User " + username + " not found.");
    }
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) User(org.springframework.security.core.userdetails.User) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) HashSet(java.util.HashSet)

Example 7 with UsernameNotFoundException

use of org.springframework.security.core.userdetails.UsernameNotFoundException in project service-authorization by reportportal.

the class DatabaseUserDetailsService method loadUserByUsername.

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    UserRoleDetails userEntity = userRepository.aggregateUserProjects(username.toLowerCase());
    if (null == userEntity || null == userEntity.getUser()) {
        throw new UsernameNotFoundException("Username '" + username + "' not found");
    }
    String login = userEntity.getUser().getLogin();
    String password = userEntity.getUser().getPassword() == null ? "" : userEntity.getUser().getPassword();
    org.springframework.security.core.userdetails.User u = new org.springframework.security.core.userdetails.User(login, password, true, true, true, true, AuthUtils.AS_AUTHORITIES.apply(userEntity.getUser().getRole()));
    return new ReportPortalUser(u, userEntity.getProjects().stream().collect(Collectors.toMap(UserRoleDetails.ProjectDetails::getProject, UserRoleDetails.ProjectDetails::getProjectRole)));
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) User(com.epam.ta.reportportal.database.entity.user.User) UserRoleDetails(com.epam.ta.reportportal.database.entity.UserRoleDetails)

Example 8 with UsernameNotFoundException

use of org.springframework.security.core.userdetails.UsernameNotFoundException in project nifi by apache.

the class LdapProvider method authenticate.

@Override
public final AuthenticationResponse authenticate(final LoginCredentials credentials) throws InvalidLoginCredentialsException, IdentityAccessException {
    if (provider == null) {
        throw new IdentityAccessException("The LDAP authentication provider is not initialized.");
    }
    try {
        // perform the authentication
        final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(credentials.getUsername(), credentials.getPassword());
        final Authentication authentication = provider.authenticate(token);
        // use dn if configured
        if (IdentityStrategy.USE_DN.equals(identityStrategy)) {
            // attempt to get the ldap user details to get the DN
            if (authentication.getPrincipal() instanceof LdapUserDetails) {
                final LdapUserDetails userDetails = (LdapUserDetails) authentication.getPrincipal();
                return new AuthenticationResponse(userDetails.getDn(), credentials.getUsername(), expiration, issuer);
            } else {
                logger.warn(String.format("Unable to determine user DN for %s, using username.", authentication.getName()));
                return new AuthenticationResponse(authentication.getName(), credentials.getUsername(), expiration, issuer);
            }
        } else {
            return new AuthenticationResponse(authentication.getName(), credentials.getUsername(), expiration, issuer);
        }
    } catch (final BadCredentialsException | UsernameNotFoundException | AuthenticationException e) {
        throw new InvalidLoginCredentialsException(e.getMessage(), e);
    } catch (final Exception e) {
        // there appears to be a bug that generates a InternalAuthenticationServiceException wrapped around an AuthenticationException. this
        // shouldn't be the case as they the service exception suggestions that something was wrong with the service. while the authentication
        // exception suggests that username and/or credentials were incorrect. checking the cause seems to address this scenario.
        final Throwable cause = e.getCause();
        if (cause instanceof AuthenticationException) {
            throw new InvalidLoginCredentialsException(e.getMessage(), e);
        }
        logger.error(e.getMessage());
        if (logger.isDebugEnabled()) {
            logger.debug(StringUtils.EMPTY, e);
        }
        throw new IdentityAccessException("Unable to validate the supplied credentials. Please contact the system administrator.", e);
    }
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) AuthenticationException(org.springframework.ldap.AuthenticationException) Authentication(org.springframework.security.core.Authentication) InvalidLoginCredentialsException(org.apache.nifi.authentication.exception.InvalidLoginCredentialsException) LdapUserDetails(org.springframework.security.ldap.userdetails.LdapUserDetails) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) IdentityAccessException(org.apache.nifi.authentication.exception.IdentityAccessException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationResponse(org.apache.nifi.authentication.AuthenticationResponse) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationException(org.springframework.ldap.AuthenticationException) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) KeyStoreException(java.security.KeyStoreException) IdentityAccessException(org.apache.nifi.authentication.exception.IdentityAccessException) ProviderCreationException(org.apache.nifi.authentication.exception.ProviderCreationException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) ProviderDestructionException(org.apache.nifi.authentication.exception.ProviderDestructionException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) InvalidLoginCredentialsException(org.apache.nifi.authentication.exception.InvalidLoginCredentialsException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 9 with UsernameNotFoundException

use of org.springframework.security.core.userdetails.UsernameNotFoundException in project webofneeds by researchstudio-sat.

the class WebIdUserDetailsService method loadUserDetails.

@Override
public UserDetails loadUserDetails(final PreAuthenticatedAuthenticationToken token) throws UsernameNotFoundException {
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    String principal = (String) token.getPrincipal();
    Certificate certificate = (Certificate) token.getCredentials();
    logger.debug("Adding userDetails for '" + principal + "'");
    URI webID = null;
    try {
        webID = new URI(principal);
    } catch (URISyntaxException e) {
        throw new BadCredentialsException("Principal of X.509 Certificate must be a WebId URI. Actual value: '" + principal + "'");
    }
    // at this point, we know that a client certificate was presented. Grant this role:
    List<GrantedAuthority> authorities = new ArrayList<>(3);
    authorities.add(new SimpleGrantedAuthority("ROLE_CLIENT_CERTIFICATE_PRESENTED"));
    logger.debug("verifying webId '" + principal + "'");
    try {
        if (webIDVerificationAgent.verify(certificate.getPublicKey(), webID)) {
            authorities.add(new SimpleGrantedAuthority("ROLE_WEBID"));
            logger.debug("webId '" + principal + "' successfully verified - ROLE_WEBID granted");
        } else {
            logger.debug("could not verify webId '" + principal + "'. ROLE_WEBID not granted");
        }
    } catch (Exception e) {
        logger.debug("could not verify webId '" + principal + "' because of an error during verification. ROLE_WEBID " + "not granted. Cause is logged", e);
    }
    stopWatch.stop();
    logger.debug("webID check took " + stopWatch.getLastTaskTimeMillis() + " millis");
    return new WebIdUserDetails(webID, authorities);
}
Also used : SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) ArrayList(java.util.ArrayList) URISyntaxException(java.net.URISyntaxException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) URI(java.net.URI) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) URISyntaxException(java.net.URISyntaxException) StopWatch(org.springframework.util.StopWatch) Certificate(java.security.cert.Certificate)

Example 10 with UsernameNotFoundException

use of org.springframework.security.core.userdetails.UsernameNotFoundException in project zhcet-web by zhcet-amu.

the class FirebaseAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!firebaseService.canProceed())
        // Firebase is disabled, so we cannot proceed
        return null;
    String token = authentication.getCredentials().toString();
    if (Strings.isNullOrEmpty(token))
        // Cannot parse empty token
        return null;
    try {
        FirebaseToken decodedToken = FirebaseService.getToken(token);
        log.debug("User Claims: {}", decodedToken.getClaims());
        UserDetails user = retrieveUser(decodedToken);
        if (user == null)
            throwBadCredentialsException();
        userDetailsChecker.check(user);
        if (user instanceof UserAuth) {
            firebaseAccountMergeService.mergeFirebaseDetails((UserAuth) user, decodedToken);
        } else {
            log.warn("User {} is not of UserAuth Type", user);
        }
        return createSuccessAuthentication(user, authentication);
    } catch (InterruptedException | ExecutionException e) {
        log.warn("Unable to decode Firebase token");
        throwBadCredentialsException();
    } catch (UsernameNotFoundException une) {
        throwBadCredentialsException();
    }
    return null;
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) FirebaseToken(com.google.firebase.auth.FirebaseToken) UserDetails(org.springframework.security.core.userdetails.UserDetails) UserAuth(amu.zhcet.auth.UserAuth) ExecutionException(java.util.concurrent.ExecutionException)

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