Search in sources :

Example 1 with GroupCollectionPage

use of com.microsoft.graph.requests.GroupCollectionPage in project azure-ad-plugin by jenkinsci.

the class AzureSecurityRealm method loadGroupByDisplayName.

@CheckForNull
private Group loadGroupByDisplayName(String groupName) {
    LinkedList<Option> requestOptions = new LinkedList<>();
    String encodedGroupName = groupName.replace("'", "''");
    try {
        encodedGroupName = URLEncoder.encode(encodedGroupName, StandardCharsets.UTF_8.name());
    } catch (UnsupportedEncodingException e) {
        LOGGER.log(Level.WARNING, "Failed to url encode query, group name was: " + groupName);
    }
    String query = String.format("\"displayName:%s\"", encodedGroupName);
    requestOptions.add(new QueryOption("$search", query));
    requestOptions.add(new HeaderOption("ConsistencyLevel", "eventual"));
    GroupCollectionPage groupCollectionPage = getAzureClient().groups().buildRequest(requestOptions).select("id,displayName").get();
    assert groupCollectionPage != null;
    List<Group> currentPage = groupCollectionPage.getCurrentPage();
    Group group = null;
    if (currentPage.size() > 1) {
        String groupIds = currentPage.stream().map(groupO -> groupO.id).collect(Collectors.joining(","));
        throw new UsernameNotFoundException("Multiple matches found for group display name, " + "this must be unique: " + groupIds);
    } else if (currentPage.size() == 1) {
        group = currentPage.get(0);
    }
    return group;
}
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) Group(com.microsoft.graph.models.Group) UnsupportedEncodingException(java.io.UnsupportedEncodingException) QueryOption(com.microsoft.graph.options.QueryOption) GroupCollectionPage(com.microsoft.graph.requests.GroupCollectionPage) HeaderOption(com.microsoft.graph.options.HeaderOption) QueryOption(com.microsoft.graph.options.QueryOption) Option(com.microsoft.graph.options.Option) LinkedList(java.util.LinkedList) HeaderOption(com.microsoft.graph.options.HeaderOption) CheckForNull(edu.umd.cs.findbugs.annotations.CheckForNull)

Example 2 with GroupCollectionPage

use of com.microsoft.graph.requests.GroupCollectionPage in project msgraph-beta-sdk-java by microsoftgraph.

the class UserTests method castTest.

@Test
public void castTest() {
    final GroupCollectionPage groups = graphServiceClient.groups().buildRequest().top(1).get();
    final Group group = groups.getCurrentPage().get(0);
    final UserCollectionPage usersPage = graphServiceClient.groups(group.id).membersAsUser().buildRequest().get();
    assertNotNull(usersPage);
    final DirectoryObjectCollectionWithReferencesPage testUserCollection = graphServiceClient.groups(group.id).members().buildRequest().top(1).get();
    final DirectoryObject testUser = testUserCollection.getCurrentPage().get(0);
    final User user = graphServiceClient.groups(group.id).membersAsUser(testUser.id).buildRequest().get();
    assertNotNull(user);
}
Also used : Group(com.microsoft.graph.models.Group) User(com.microsoft.graph.models.User) UserCollectionPage(com.microsoft.graph.requests.UserCollectionPage) GroupCollectionPage(com.microsoft.graph.requests.GroupCollectionPage) DirectoryObjectCollectionWithReferencesPage(com.microsoft.graph.requests.DirectoryObjectCollectionWithReferencesPage) DirectoryObject(com.microsoft.graph.models.DirectoryObject) Test(org.junit.jupiter.api.Test)

Example 3 with GroupCollectionPage

use of com.microsoft.graph.requests.GroupCollectionPage in project azure-ad-plugin by jenkinsci.

the class AzureAdMatrixAuthorizationStrategy method searchAndGenerateCandidates.

static AutoCompletionCandidates searchAndGenerateCandidates(String prefix) {
    final int maxCandidates = 20;
    if (StringUtils.isEmpty(prefix)) {
        return null;
    }
    SecurityRealm realm = Jenkins.get().getSecurityRealm();
    if (!(realm instanceof AzureSecurityRealm)) {
        return null;
    }
    GraphServiceClient<Request> graphClient = ((AzureSecurityRealm) realm).getAzureClient();
    List<AzureObject> candidates = new ArrayList<>();
    LOGGER.info("search users with prefix: " + prefix);
    try {
        UserCollectionPage users = lookupUsers(prefix, graphClient);
        for (User user : users.getCurrentPage()) {
            candidates.add(new AzureObject(user.id, user.displayName));
            if (candidates.size() > maxCandidates) {
                break;
            }
        }
        if (candidates.size() < maxCandidates) {
            GroupCollectionPage groupCollectionPage = lookupGroups(prefix, graphClient);
            for (Group group : groupCollectionPage.getCurrentPage()) {
                candidates.add(new AzureObject(group.id, group.displayName));
            }
        }
    } catch (Exception e) {
        LOGGER.log(Level.WARNING, "Do not have sufficient privileges to search related users or groups", e);
    }
    AutoCompletionCandidates c = new AutoCompletionCandidates();
    for (AzureObject obj : candidates) {
        String candidateText = ObjId2FullSidMap.generateFullSid(obj.getDisplayName(), obj.getObjectId());
        c.add(candidateText);
    }
    return c;
}
Also used : AutoCompletionCandidates(hudson.model.AutoCompletionCandidates) Group(com.microsoft.graph.models.Group) ItemGroup(hudson.model.ItemGroup) User(com.microsoft.graph.models.User) SecurityRealm(hudson.security.SecurityRealm) Request(okhttp3.Request) ArrayList(java.util.ArrayList) UserCollectionPage(com.microsoft.graph.requests.UserCollectionPage) GroupCollectionPage(com.microsoft.graph.requests.GroupCollectionPage)

Example 4 with GroupCollectionPage

use of com.microsoft.graph.requests.GroupCollectionPage in project msgraph-sdk-java by microsoftgraph.

the class UserTests method castTest.

@Test
public void castTest() {
    final GroupCollectionPage groups = graphServiceClient.groups().buildRequest().top(1).get();
    final Group group = groups.getCurrentPage().get(0);
    final UserCollectionPage usersPage = graphServiceClient.groups(group.id).membersAsUser().buildRequest().get();
    assertNotNull(usersPage);
    final DirectoryObjectCollectionWithReferencesPage testUserCollection = graphServiceClient.groups(group.id).members().buildRequest().top(1).get();
    final DirectoryObject testUser = testUserCollection.getCurrentPage().get(0);
    final User user = graphServiceClient.groups(group.id).membersAsUser(testUser.id).buildRequest().get();
    assertNotNull(user);
}
Also used : Group(com.microsoft.graph.models.Group) User(com.microsoft.graph.models.User) UserCollectionPage(com.microsoft.graph.requests.UserCollectionPage) GroupCollectionPage(com.microsoft.graph.requests.GroupCollectionPage) DirectoryObjectCollectionWithReferencesPage(com.microsoft.graph.requests.DirectoryObjectCollectionWithReferencesPage) DirectoryObject(com.microsoft.graph.models.DirectoryObject) Test(org.junit.jupiter.api.Test)

Aggregations

Group (com.microsoft.graph.models.Group)4 GroupCollectionPage (com.microsoft.graph.requests.GroupCollectionPage)4 User (com.microsoft.graph.models.User)3 UserCollectionPage (com.microsoft.graph.requests.UserCollectionPage)3 DirectoryObject (com.microsoft.graph.models.DirectoryObject)2 DirectoryObjectCollectionWithReferencesPage (com.microsoft.graph.requests.DirectoryObjectCollectionWithReferencesPage)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 HeaderOption (com.microsoft.graph.options.HeaderOption)1