Search in sources :

Example 1 with UserMayOrMayNotExistException2

use of hudson.security.UserMayOrMayNotExistException2 in project jenkins by jenkinsci.

the class User method getUserDetailsForImpersonation2.

/**
 * This method checks with {@link SecurityRealm} if the user is a valid user that can login to the security realm.
 * If {@link SecurityRealm} is a kind that does not support querying information about other users, this will
 * use {@link LastGrantedAuthoritiesProperty} to pick up the granted authorities as of the last time the user has
 * logged in.
 *
 * @return userDetails for the user, in case he's not found but seems legitimate, we provide a userDetails with minimum access
 * @throws UsernameNotFoundException If this user is not a valid user in the backend {@link SecurityRealm}.
 * @since 2.266
 */
@NonNull
public UserDetails getUserDetailsForImpersonation2() throws UsernameNotFoundException {
    ImpersonatingUserDetailsService2 userDetailsService = new ImpersonatingUserDetailsService2(Jenkins.get().getSecurityRealm().getSecurityComponents().userDetails2);
    try {
        UserDetails userDetails = userDetailsService.loadUserByUsername(id);
        LOGGER.log(Level.FINE, "Impersonation of the user {0} was a success", id);
        return userDetails;
    } catch (UserMayOrMayNotExistException2 e) {
        LOGGER.log(Level.FINE, "The user {0} may or may not exist in the SecurityRealm, so we provide minimum access", id);
    } catch (UsernameNotFoundException e) {
        if (ALLOW_NON_EXISTENT_USER_TO_LOGIN) {
            LOGGER.log(Level.FINE, "The user {0} was not found in the SecurityRealm but we are required to let it pass, due to ALLOW_NON_EXISTENT_USER_TO_LOGIN", id);
        } else {
            LOGGER.log(Level.FINE, "The user {0} was not found in the SecurityRealm", id);
            throw e;
        }
    }
    return new LegitimateButUnknownUserDetails(id);
}
Also used : ImpersonatingUserDetailsService2(jenkins.security.ImpersonatingUserDetailsService2) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) UserMayOrMayNotExistException2(hudson.security.UserMayOrMayNotExistException2) UserDetails(org.springframework.security.core.userdetails.UserDetails) NonNull(edu.umd.cs.findbugs.annotations.NonNull)

Example 2 with UserMayOrMayNotExistException2

use of hudson.security.UserMayOrMayNotExistException2 in project azure-ad-plugin by jenkinsci.

the class AzureSecurityRealm method createSecurityComponents.

@Override
public SecurityComponents createSecurityComponents() {
    return new SecurityComponents((AuthenticationManager) authentication -> {
        if (authentication instanceof AzureAuthenticationToken) {
            return authentication;
        }
        throw new BadCredentialsException("Unexpected authentication type: " + authentication);
    }, username -> {
        if (username == null) {
            throw new UserMayOrMayNotExistException2("Can't find a user with no username");
        }
        if (isDisableGraphIntegration()) {
            throw new UserMayOrMayNotExistException2("Can't lookup a user if graph integration is disabled");
        }
        AzureAdUser azureAdUser = caches.get(username, (cacheKey) -> {
            GraphServiceClient<Request> azureClient = getAzureClient();
            String userId = ObjId2FullSidMap.extractObjectId(username);
            if (userId == null) {
                userId = username;
            }
            // as we look up by object id we don't know if it's a user or a group :(
            try {
                com.microsoft.graph.models.User activeDirectoryUser = azureClient.users(userId).buildRequest().get();
                if (activeDirectoryUser != null & activeDirectoryUser.id == null) {
                    // known to happen when subject is a group with display name only and starts with a #
                    return null;
                }
                AzureAdUser user = requireNonNull(AzureAdUser.createFromActiveDirectoryUser(activeDirectoryUser));
                List<AzureAdGroup> groups = AzureCachePool.get(azureClient).getBelongingGroupsByOid(user.getObjectID());
                user.setAuthorities(groups);
                return user;
            } catch (GraphServiceException e) {
                if (e.getResponseCode() == NOT_FOUND) {
                    return null;
                } else if (e.getResponseCode() == BAD_REQUEST) {
                    if (LOGGER.isLoggable(Level.FINE)) {
                        LOGGER.log(Level.FINE, "Failed to lookup user with userid '" + userId, e);
                    } else {
                        LOGGER.log(Level.WARNING, "Failed to lookup user with userid '" + userId + "'." + " Enable 'Fine' Logging for more information.");
                    }
                    return null;
                }
                throw e;
            }
        });
        if (azureAdUser == null) {
            throw new UsernameNotFoundException("Cannot find user: " + username);
        }
        return azureAdUser;
    });
}
Also used : HierarchicalStreamWriter(com.thoughtworks.xstream.io.HierarchicalStreamWriter) FilterChain(javax.servlet.FilterChain) ServiceBuilder(com.github.scribejava.core.builder.ServiceBuilder) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) AccessToken(com.azure.core.credential.AccessToken) UUIDValidator(com.microsoft.jenkins.azuread.utils.UUIDValidator) Mailer(hudson.tasks.Mailer) DataBoundConstructor(org.kohsuke.stapler.DataBoundConstructor) ServletException(javax.servlet.ServletException) HttpRedirect(org.kohsuke.stapler.HttpRedirect) OAuth20Service(com.github.scribejava.core.oauth.OAuth20Service) StringUtils(org.apache.commons.lang3.StringUtils) Collections.singletonList(java.util.Collections.singletonList) HttpClients(com.microsoft.graph.httpcore.HttpClients) SecurityRealm(hudson.security.SecurityRealm) Proxy(java.net.Proxy) Group(com.microsoft.graph.models.Group) NonNull(edu.umd.cs.findbugs.annotations.NonNull) Map(java.util.Map) ClientSecretCredentialBuilder(com.azure.identity.ClientSecretCredentialBuilder) GroupDetails(hudson.security.GroupDetails) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) TokenCredentialAuthProvider(com.microsoft.graph.authentication.TokenCredentialAuthProvider) InvalidJwtException(org.jose4j.jwt.consumer.InvalidJwtException) Converter(com.thoughtworks.xstream.converters.Converter) Request(okhttp3.Request) ListBoxModel(hudson.util.ListBoxModel) HttpResponse(org.kohsuke.stapler.HttpResponse) Collections.emptyList(java.util.Collections.emptyList) Jenkins(jenkins.model.Jenkins) MarshallingContext(com.thoughtworks.xstream.converters.MarshallingContext) JenkinsJVM(jenkins.util.JenkinsJVM) Credentials(okhttp3.Credentials) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Header(org.kohsuke.stapler.Header) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) List(java.util.List) HierarchicalStreamReader(com.thoughtworks.xstream.io.HierarchicalStreamReader) UserMayOrMayNotExistException2(hudson.security.UserMayOrMayNotExistException2) RandomStringUtils(org.apache.commons.lang3.RandomStringUtils) HeaderOption(com.microsoft.graph.options.HeaderOption) Authentication(org.springframework.security.core.Authentication) UnsupportedEncodingException(java.io.UnsupportedEncodingException) GroupCollectionPage(com.microsoft.graph.requests.GroupCollectionPage) GraphServiceClient(com.microsoft.graph.requests.GraphServiceClient) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) QueryParameter(org.kohsuke.stapler.QueryParameter) StaplerRequest(org.kohsuke.stapler.StaplerRequest) Supplier(com.google.common.base.Supplier) HashMap(java.util.HashMap) ClientSecretCredential(com.azure.identity.ClientSecretCredential) Cache(com.github.benmanes.caffeine.cache.Cache) CrumbExclusion(hudson.security.csrf.CrumbExclusion) UserProperty(hudson.tasks.Mailer.UserProperty) AZURE_CHINA(com.microsoft.jenkins.azuread.AzureEnvironment.AZURE_CHINA) AzureEnvironment.getServiceRoot(com.microsoft.jenkins.azuread.AzureEnvironment.getServiceRoot) TokenRequestContext(com.azure.core.credential.TokenRequestContext) Level(java.util.logging.Level) HttpServletRequest(javax.servlet.http.HttpServletRequest) Objects.requireNonNull(java.util.Objects.requireNonNull) Suppliers(com.google.common.base.Suppliers) Extension(hudson.Extension) User(hudson.model.User) LinkedList(java.util.LinkedList) Util(hudson.Util) Caffeine(com.github.benmanes.caffeine.cache.Caffeine) UnmarshallingContext(com.thoughtworks.xstream.converters.UnmarshallingContext) QueryOption(com.microsoft.graph.options.QueryOption) AuthenticationManager(org.springframework.security.authentication.AuthenticationManager) ProxyConfiguration(hudson.ProxyConfiguration) FormValidation(hudson.util.FormValidation) HttpResponses(org.kohsuke.stapler.HttpResponses) Descriptor(hudson.model.Descriptor) DataBoundSetter(org.kohsuke.stapler.DataBoundSetter) HttpClientRetriever(io.jenkins.plugins.azuresdk.HttpClientRetriever) HttpServletResponse(javax.servlet.http.HttpServletResponse) GraphServiceException(com.microsoft.graph.http.GraphServiceException) IOException(java.io.IOException) AZURE_US_GOVERNMENT_L4(com.microsoft.jenkins.azuread.AzureEnvironment.AZURE_US_GOVERNMENT_L4) AZURE_GERMANY(com.microsoft.jenkins.azuread.AzureEnvironment.AZURE_GERMANY) AZURE_US_GOVERNMENT_L5(com.microsoft.jenkins.azuread.AzureEnvironment.AZURE_US_GOVERNMENT_L5) AzureAdApi(com.microsoft.jenkins.azuread.scribe.AzureAdApi) SecurityListener(jenkins.security.SecurityListener) AzureEnvironment.getAuthorityHost(com.microsoft.jenkins.azuread.AzureEnvironment.getAuthorityHost) TimeUnit(java.util.concurrent.TimeUnit) Option(com.microsoft.graph.options.Option) URLEncoder(java.net.URLEncoder) OkHttpClient(okhttp3.OkHttpClient) JwtClaims(org.jose4j.jwt.JwtClaims) AZURE_PUBLIC_CLOUD(com.microsoft.jenkins.azuread.AzureEnvironment.AZURE_PUBLIC_CLOUD) Secret(hudson.util.Secret) CheckForNull(edu.umd.cs.findbugs.annotations.CheckForNull) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) GraphServiceException(com.microsoft.graph.http.GraphServiceException) Request(okhttp3.Request) StaplerRequest(org.kohsuke.stapler.StaplerRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) UserMayOrMayNotExistException2(hudson.security.UserMayOrMayNotExistException2)

Example 3 with UserMayOrMayNotExistException2

use of hudson.security.UserMayOrMayNotExistException2 in project azure-ad-plugin by jenkinsci.

the class AzureSecurityRealm method loadGroupByGroupname2.

/**
 * {@inheritDoc}
 */
@Override
public GroupDetails loadGroupByGroupname2(String groupName, boolean fetchMembers) {
    if (isDisableGraphIntegration()) {
        throw new UserMayOrMayNotExistException2("Can't lookup a group if graph integration is disabled");
    }
    GraphServiceClient<Request> azureClient = getAzureClient();
    String groupId = ObjId2FullSidMap.extractObjectId(groupName);
    if (groupId == null) {
        // just an object id on it's own?
        groupId = groupName;
    }
    Group group;
    if (UUIDValidator.isValidUUID(groupId)) {
        group = azureClient.groups(groupId).buildRequest().get();
    } else {
        group = loadGroupByDisplayName(groupName);
    }
    if (group == null || group.id == null) {
        throw new UsernameNotFoundException("Group: " + groupName + " not found");
    }
    return new AzureAdGroupDetails(group.id, group.displayName);
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) UserMayOrMayNotExistException2(hudson.security.UserMayOrMayNotExistException2) Group(com.microsoft.graph.models.Group) Request(okhttp3.Request) StaplerRequest(org.kohsuke.stapler.StaplerRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest)

Example 4 with UserMayOrMayNotExistException2

use of hudson.security.UserMayOrMayNotExistException2 in project crowd2-plugin by jenkinsci.

the class CrowdMailAddressResolverImpl method findMailAddressFor.

/**
 * {@inheritDoc}
 *
 * @see hudson.tasks.MailAddressResolver#findMailAddressFor(hudson.model.User)
 */
@Override
public String findMailAddressFor(User u) {
    String mail = null;
    SecurityRealm realm = getSecurityRealm();
    if (realm instanceof CrowdSecurityRealm) {
        try {
            String userId = u.getId();
            LOG.log(Level.FINE, "Looking up mail address for user: {0}", userId);
            CrowdUser details = (CrowdUser) realm.loadUserByUsername2(userId);
            mail = details.getEmailAddress();
        } catch (UserMayOrMayNotExistException2 ex) {
            LOG.log(Level.SEVERE, "User do not exist, unable to look up email address", ex);
        } catch (UsernameNotFoundException ex) {
            LOG.log(Level.INFO, "Failed to look up email address in Crowd");
        }
    }
    return mail;
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) UserMayOrMayNotExistException2(hudson.security.UserMayOrMayNotExistException2) SecurityRealm(hudson.security.SecurityRealm)

Aggregations

UserMayOrMayNotExistException2 (hudson.security.UserMayOrMayNotExistException2)4 UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)4 Group (com.microsoft.graph.models.Group)2 SecurityRealm (hudson.security.SecurityRealm)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 Request (okhttp3.Request)2 StaplerRequest (org.kohsuke.stapler.StaplerRequest)2 AccessToken (com.azure.core.credential.AccessToken)1 TokenRequestContext (com.azure.core.credential.TokenRequestContext)1 ClientSecretCredential (com.azure.identity.ClientSecretCredential)1 ClientSecretCredentialBuilder (com.azure.identity.ClientSecretCredentialBuilder)1 Cache (com.github.benmanes.caffeine.cache.Cache)1 Caffeine (com.github.benmanes.caffeine.cache.Caffeine)1 ServiceBuilder (com.github.scribejava.core.builder.ServiceBuilder)1 OAuth20Service (com.github.scribejava.core.oauth.OAuth20Service)1 Supplier (com.google.common.base.Supplier)1 Suppliers (com.google.common.base.Suppliers)1 TokenCredentialAuthProvider (com.microsoft.graph.authentication.TokenCredentialAuthProvider)1 GraphServiceException (com.microsoft.graph.http.GraphServiceException)1 HttpClients (com.microsoft.graph.httpcore.HttpClients)1