Search in sources :

Example 26 with UsernameNotFoundException

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

the class LdapUserProviderInstance method loadUserFromLdap.

/**
 * Loads a user from LDAP.
 *
 * @param userName
 *          the username
 * @return the user
 */
protected User loadUserFromLdap(String userName) {
    if (delegate == null || cache == null) {
        throw new IllegalStateException("The LDAP user detail service has not yet been configured");
    }
    ldapLoads.incrementAndGet();
    UserDetails userDetails = null;
    Thread currentThread = Thread.currentThread();
    ClassLoader originalClassloader = currentThread.getContextClassLoader();
    try {
        currentThread.setContextClassLoader(LdapUserProviderFactory.class.getClassLoader());
        try {
            userDetails = delegate.loadUserByUsername(userName);
        } catch (UsernameNotFoundException e) {
            cache.put(userName, nullToken);
            return null;
        }
        JaxbOrganization jaxbOrganization = JaxbOrganization.fromOrganization(organization);
        // Get the roles and add the extra roles
        Collection<GrantedAuthority> authorities = new HashSet<>();
        authorities.addAll(userDetails.getAuthorities());
        authorities.addAll(setExtraRoles);
        Set<JaxbRole> roles = new HashSet<>();
        if (authorities != null) {
            /*
         * Please note the prefix logic for roles:
         *
         * - Roles that start with any of the "exclude prefixes" are left intact
         * - In any other case, the "role prefix" is prepended to the roles read from LDAP
         *
         * This only applies to the prefix addition. The conversion to uppercase is independent from these
         * considerations
         */
            for (GrantedAuthority authority : authorities) {
                String strAuthority = authority.getAuthority();
                boolean hasExcludePrefix = false;
                for (String excludePrefix : setExcludePrefixes) {
                    if (strAuthority.startsWith(excludePrefix)) {
                        hasExcludePrefix = true;
                        break;
                    }
                }
                if (!hasExcludePrefix) {
                    strAuthority = rolePrefix + strAuthority;
                }
                // Finally, add the role itself
                roles.add(new JaxbRole(strAuthority, jaxbOrganization));
            }
        }
        User user = new JaxbUser(userDetails.getUsername(), PROVIDER_NAME, jaxbOrganization, roles);
        cache.put(userName, user);
        return user;
    } finally {
        currentThread.setContextClassLoader(originalClassloader);
    }
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) User(org.opencastproject.security.api.User) JaxbUser(org.opencastproject.security.api.JaxbUser) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) JaxbOrganization(org.opencastproject.security.api.JaxbOrganization) JaxbUser(org.opencastproject.security.api.JaxbUser) UserDetails(org.springframework.security.core.userdetails.UserDetails) JaxbRole(org.opencastproject.security.api.JaxbRole) HashSet(java.util.HashSet)

Example 27 with UsernameNotFoundException

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

the class UserAndRoleDirectoryServiceImpl method loadUserByUsername.

/**
 * {@inheritDoc}
 *
 * @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
 */
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, org.springframework.dao.DataAccessException {
    User user = loadUser(userName);
    if (user == null)
        throw new UsernameNotFoundException(userName);
    // Store the user in the security service
    securityService.setUser(user);
    Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
    for (Role role : user.getRoles()) {
        authorities.add(new SimpleGrantedAuthority(role.getName()));
    }
    // Add additional roles from role providers
    if (!InMemoryUserAndRoleProvider.PROVIDER_NAME.equals(user.getProvider())) {
        for (RoleProvider roleProvider : roleProviders) {
            List<Role> rolesForUser = roleProvider.getRolesForUser(userName);
            for (Role role : rolesForUser) authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
    }
    authorities.add(new SimpleGrantedAuthority(securityService.getOrganization().getAnonymousRole()));
    // need a non null password to instantiate org.springframework.security.core.userdetails.User
    // but CAS authenticated users have no password
    String password = user.getPassword() == null ? DEFAULT_PASSWORD : user.getPassword();
    return new org.springframework.security.core.userdetails.User(user.getUsername(), password, user.canLogin(), true, true, true, authorities);
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) JaxbRole(org.opencastproject.security.api.JaxbRole) Role(org.opencastproject.security.api.Role) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) User(org.opencastproject.security.api.User) JaxbUser(org.opencastproject.security.api.JaxbUser) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) RoleProvider(org.opencastproject.security.api.RoleProvider) HashSet(java.util.HashSet)

Example 28 with UsernameNotFoundException

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

the class LtiLaunchAuthenticationHandler method createAuthentication.

/**
 * {@inheritDoc}
 *
 * @see org.springframework.security.oauth.provider.OAuthAuthenticationHandler#createAuthentication(javax.servlet.http.HttpServletRequest,
 *      org.springframework.security.oauth.provider.ConsumerAuthentication,
 *      org.springframework.security.oauth.provider.token.OAuthAccessProviderToken)
 */
@Override
public Authentication createAuthentication(HttpServletRequest request, ConsumerAuthentication authentication, OAuthAccessProviderToken authToken) {
    // The User ID must be provided by the LTI consumer
    String userIdFromConsumer = request.getParameter(LTI_USER_ID_PARAM);
    if (StringUtils.isBlank(userIdFromConsumer)) {
        logger.warn("Received authentication request without user id ({})", LTI_USER_ID_PARAM);
        return null;
    }
    // Get the consumer guid if provided
    String consumerGUID = request.getParameter(LTI_CONSUMER_GUID);
    // This is an optional field, so it could be blank
    if (StringUtils.isBlank(consumerGUID)) {
        consumerGUID = "UnknownConsumer";
    }
    // We need to construct a complex ID to avoid confusion
    userIdFromConsumer = LTI_USER_ID_PREFIX + LTI_ID_DELIMITER + consumerGUID + LTI_ID_DELIMITER + userIdFromConsumer;
    // if this is a trusted consumer we trust their details
    String oaAuthKey = request.getParameter("oauth_consumer_key");
    if (highlyTrustedKeys.contains(oaAuthKey)) {
        logger.debug("{} is a trusted key", oaAuthKey);
        // If supplied we use the human readable name
        String suppliedEid = request.getParameter("lis_person_sourcedid");
        // This is an optional field it could be null
        if (StringUtils.isNotBlank(suppliedEid)) {
            userIdFromConsumer = suppliedEid;
        } else {
            // if no eid is set we use the supplied ID
            userIdFromConsumer = request.getParameter(LTI_USER_ID_PARAM);
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("LTI user id is : {}", userIdFromConsumer);
    }
    UserDetails userDetails = null;
    Collection<GrantedAuthority> userAuthorities = null;
    try {
        userDetails = userDetailsService.loadUserByUsername(userIdFromConsumer);
        // userDetails returns a Collection<? extends GrantedAuthority>, which cannot be directly casted to a
        // Collection<GrantedAuthority>.
        // On the other hand, one cannot add non-null elements or modify the existing ones in a Collection<? extends
        // GrantedAuthority>. Therefore, we *must* instantiate a new Collection<GrantedAuthority> (an ArrayList in this
        // case) and populate it with whatever elements are returned by getAuthorities()
        userAuthorities = new HashSet<GrantedAuthority>(userDetails.getAuthorities());
        // we still need to enrich this user with the LTI Roles
        String roles = request.getParameter(ROLES);
        String context = request.getParameter(CONTEXT_ID);
        enrichRoleGrants(roles, context, userAuthorities);
    } catch (UsernameNotFoundException e) {
        // This user is known to the tool consumer, but not to Opencast. Create a user "on the fly"
        userAuthorities = new HashSet<GrantedAuthority>();
        // We should add the authorities passed in from the tool consumer?
        String roles = request.getParameter(ROLES);
        String context = request.getParameter(CONTEXT_ID);
        enrichRoleGrants(roles, context, userAuthorities);
        logger.info("Returning user with {} authorities", userAuthorities.size());
        userDetails = new User(userIdFromConsumer, "oauth", true, true, true, true, userAuthorities);
    }
    // All users need the OAUTH, USER and ANONYMOUS roles
    userAuthorities.add(new SimpleGrantedAuthority(ROLE_OAUTH_USER));
    userAuthorities.add(new SimpleGrantedAuthority("ROLE_USER"));
    userAuthorities.add(new SimpleGrantedAuthority("ROLE_ANONYMOUS"));
    Authentication ltiAuth = new PreAuthenticatedAuthenticationToken(userDetails, authentication.getCredentials(), userAuthorities);
    SecurityContextHolder.getContext().setAuthentication(ltiAuth);
    return ltiAuth;
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) UserDetails(org.springframework.security.core.userdetails.UserDetails) User(org.springframework.security.core.userdetails.User) ConsumerAuthentication(org.springframework.security.oauth.provider.ConsumerAuthentication) Authentication(org.springframework.security.core.Authentication) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) HashSet(java.util.HashSet)

Example 29 with UsernameNotFoundException

use of org.springframework.security.core.userdetails.UsernameNotFoundException in project FuryViewer by TheDoctor-95.

the class DomainUserDetailsService method loadUserByUsername.

@Override
@Transactional
public UserDetails loadUserByUsername(final String login) {
    log.debug("Authenticating {}", login);
    String lowercaseLogin = login.toLowerCase(Locale.ENGLISH);
    Optional<User> userFromDatabase = userRepository.findOneWithAuthoritiesByLogin(lowercaseLogin);
    return userFromDatabase.map(user -> {
        if (!user.getActivated()) {
            throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
        }
        List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream().map(authority -> new SimpleGrantedAuthority(authority.getName())).collect(Collectors.toList());
        return new org.springframework.security.core.userdetails.User(lowercaseLogin, user.getPassword(), grantedAuthorities);
    }).orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the " + "database"));
}
Also used : java.util(java.util) Logger(org.slf4j.Logger) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) LoggerFactory(org.slf4j.LoggerFactory) UserDetailsService(org.springframework.security.core.userdetails.UserDetailsService) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) Collectors(java.util.stream.Collectors) UserRepository(com.furyviewer.repository.UserRepository) GrantedAuthority(org.springframework.security.core.GrantedAuthority) Component(org.springframework.stereotype.Component) User(com.furyviewer.domain.User) UserDetails(org.springframework.security.core.userdetails.UserDetails) Transactional(org.springframework.transaction.annotation.Transactional) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) User(com.furyviewer.domain.User) Transactional(org.springframework.transaction.annotation.Transactional)

Example 30 with UsernameNotFoundException

use of org.springframework.security.core.userdetails.UsernameNotFoundException in project irida by phac-nml.

the class UserServiceImpl method loadUserByUsername.

/**
 * {@inheritDoc}
 */
@Override
@Transactional(readOnly = true)
@PreAuthorize("permitAll")
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    logger.trace("Loading user with username: [" + username + "].");
    org.springframework.security.core.userdetails.User userDetails = null;
    User u;
    try {
        u = userRepository.loadUserByUsername(username);
        userDetails = new org.springframework.security.core.userdetails.User(u.getUsername(), u.getPassword(), u.getAuthorities());
    } catch (EntityNotFoundException e) {
        throw new UsernameNotFoundException(e.getMessage());
    }
    return userDetails;
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) User(ca.corefacility.bioinformatics.irida.model.user.User) EntityNotFoundException(ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) 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