Search in sources :

Example 1 with GraphServiceClient

use of com.microsoft.graph.requests.GraphServiceClient 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)

Aggregations

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 Group (com.microsoft.graph.models.Group)1 HeaderOption (com.microsoft.graph.options.HeaderOption)1 Option (com.microsoft.graph.options.Option)1 QueryOption (com.microsoft.graph.options.QueryOption)1 GraphServiceClient (com.microsoft.graph.requests.GraphServiceClient)1 GroupCollectionPage (com.microsoft.graph.requests.GroupCollectionPage)1 AZURE_CHINA (com.microsoft.jenkins.azuread.AzureEnvironment.AZURE_CHINA)1