Skip to main content

Scripters guide to using Guest Access in Office365 to automate things

Guest access is one of the ways in Office365 of collaborating between different organizations which allows you to give certain people who are outside of your company access to a limited subset of the resources you have in the Cloud. This can be an Office365 unified Group or Microsoft Team but also other workloads like SharePoint and OneDrive can utilize this.
When it comes to scripting there are a number of value add things you can do to automate tasks for different people who have guest accounts in another tenant. The first step to automating with Guest Access is to Authenticate and generate an access token in the Guest tenant.
Getting the Guest Tenants Authorization Endpoint
Before you can authenticate you need to first obtain the Guest tenants Authorization endpoint for the tenant where the Guest Account exists in. To do this you can make a simple Get Request like the following
Invoke-WebRequest -uri ("[https://login.windows.net/{0}/.well-known/openid-configuration" -f "guestdomain.com")
this will return a JSON result that contains the Authorization endpoint for the guest tenant along with other information useful when authenticating.
While Invoke Web Request will do the job fine if you ever what to execute something like this from an Azure Run-book it better to use the httpclient object instead. Here is a simple function to get the Authorization endpoint
function Get-TenantId {
param( 
    [Parameter(Position = 1, Mandatory = $false)]
    [String]$DomainName
   
)  
Begin {
    $RequestURL = "https://login.windows.net/{0}/.well-known/openid-configuration" -f $DomainName
    Add-Type -AssemblyName System.Net.Http
    $handler = New-Object  System.Net.Http.HttpClientHandler
    $handler.CookieContainer = New-Object System.Net.CookieContainer
    $handler.AllowAutoRedirect = $true;
    $HttpClient = New-Object System.Net.Http.HttpClient($handler);
    $Header = New-Object System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")
    $HttpClient.DefaultRequestHeaders.Accept.Add($Header);
    $HttpClient.Timeout = New-Object System.TimeSpan(0, 0, 90);
    $HttpClient.DefaultRequestHeaders.TransferEncodingChunked = $false
    $Header = New-Object System.Net.Http.Headers.ProductInfoHeaderValue("Get-TenantId", "1.1")
    $HttpClient.DefaultRequestHeaders.UserAgent.Add($Header);
    $ClientResult = $HttpClient.GetAsync([Uri]$RequestURL)
    $JsonResponse = ConvertFrom-Json  $ClientResult.Result.Content.ReadAsStringAsync().Result
    return $JsonResponse.authorization_endpoint
}}
Using the ADAL
Once you have the authorization endpoint your ready to Authenticate, using the ADAL library which is a popular method you would use something like the following (where I’m using the above function to get the endpoint in @line3
Import-Module .\Microsoft.IdentityModel.Clients.ActiveDirectory.dll -Force
$PromptBehavior  =  New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters -ArgumentList Auto
$EndpointUri  =  Get-Tenantid -DomainName domain.com
$Context  =  New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext($EndpointUri)
$token  = ($Context.AcquireTokenAsync("https://graph.microsoft.com","d3590ed6-52b3-4102-aeff-aad2292ab01c","urn:ietf:wg:oauth:2.0:oob",$PromptBehavior)).Result
In the above example I’ve used the preapproved Office appId otherwise if you where to use your own AppId that would need to be authorized in the Guest tenant (which is a always a degree of difficulty when dealing with another companie's IT departments).
Once you have the Token you can then make a Request to the ./me endpoint to find a bit more about your account in the guest tenant eg
$Header = @{
        'Content-Type'  = 'application\json'
        'Authorization' = $token.CreateAuthorizationHeader()
        }
Invoke-RestMethod -Headers $Header -Uri "https://graph.microsoft.com/v1.0/me" -Method Get -ContentType "application/json" 
Or to get the Groups or Teams your a member of you can use
Invoke-RestMethod -Headers $Header -Uri "https://graph.microsoft.com/v1.0/me/memberOf" -Method Get -ContentType "application/json" 
And to get the Members or a particular Team or Group
Invoke-RestMethod -Headers $Header -Uri "https://graph.microsoft.com/v1.0/groups/938383f7-3060-4604-b3a5-cbdb0a5fc90f/members" -Method Get -ContentType "application/json"
Where the Guid (938383f7-3060-4604-b3a5-cbdb0a5fc90f in this instance) is the id you retrieved when you used me/memberOf
This gives you access to all the raw data about each of the members of a Group you might be interacting with. For some real life uses of this take a look at the module section below
Other things you can do with this which I’ll go through below are
  • Export the Group members from  a Guest Teams/Group to CSV
  • Download or Upload Files to shared Team/Group drive
  • Export the Groups Calendar to a CSV file

Using a Module

If your looking for an easier way of using Guest Access check out my Exch-Rest Module on the PowerShell Gallery https://www.powershellgallery.com/packages/Exch-Rest/3.22.0 and gitHub https://github.com/gscales/Exch-Rest . The following are samples for this module
To connect to a tenant as a Guest use
 Connect-EXRMailbox -GuestDomain guestdomain.com -MailboxName gscales@datarumble.com
You can then execute the Me and MemberOf requests using
Get-EXRMe

Get-EXRMemberOf
Export the members of a Group or Team your a member of as a Guest to CSV
The following can be used to Export the members of a Team or Unified Group in a Guest tenant to a CSV file. The Inputs you need a the SMTP address of the Group which you can get from running Get-EXRMemberOf in the Guest Tenant
$Group = Get-EXRUnifedGroups -mail guest@guestdomain.org
$GroupMembers = Get-EXRGroupMembers -GroupId $Group.id -ContactPropsOnly
$GroupMembers |  Export-Csv -path c:\temp\groupexport.csv -noTypeInformation
If you wish to include the user photo in the export you can use (although the AppId you use to connect must have access to the userphoto)
$Group = Get-EXRUnifedGroups -mail guest@guestdomain.org
$GroupMembers = Get-EXRGroupMembers -GroupId $Group.id -ContactPropsOnly
$GroupMembers |  Export-Csv -path c:\temp\groupexport.csv -noTypeInformation
Downloading a File from Group/Teams Shared Drive (Files) as a Guest
$Group = Get-EXRUnifedGroups -mail guest@guestdomain.org
$FileName = "thenameofthedoc.docs"
$File = Get-EXRGroupFiles -GroupId $Group.id -FileName $FileName
Invoke-WebRequest -Uri $File.'@microsoft.graph.downloadUrl' -OutFile ("C:\downloaddirectory\$FileName)
Export a Groups Calendar to CSV as a Guest
$Group = Get-EXRUnifedGroups -mail guest@guestdomain.org
Get-EXRGroupCalendar -GroupId $Group.id -Export | export-csv -NoTypeInformation -Path c:\temp\calendarexport.csv
By default the next 7 days is exported by the time windows can be tweaked using -starttime and -sndtime parameter in the Get-EXRGroupCalendar cmdlet
Hire me - If you would like to do something similar to this or anything else you see on my blog I'm currently available to help with any Office365,Microsoft Teams, Exchange or Active Directory related development work or scripting, please contact me at gscales@msgdevelop.com (nothing too big or small).

Popular posts from this blog

Testing and Sending email via SMTP using Opportunistic TLS and oAuth in Office365 with PowerShell

As well as EWS and Remote PowerShell (RPS) other mail protocols POP3, IMAP and SMTP have had OAuth authentication enabled in Exchange Online (Official announcement here ). A while ago I created  this script that used Opportunistic TLS to perform a Telnet style test against a SMTP server using SMTP AUTH. Now that oAuth authentication has been enabled in office365 I've updated this script to be able to use oAuth instead of SMTP Auth to test against Office365. I've also included a function to actually send a Message. Token Acquisition  To Send a Mail using oAuth you first need to get an Access token from Azure AD there are plenty of ways of doing this in PowerShell. You could use a library like MSAL or ADAL (just google your favoured method) or use a library less approach which I've included with this script . Whatever way you do this you need to make sure that your application registration  https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-

The MailboxConcurrency limit and using Batching in the Microsoft Graph API

If your getting an error such as Application is over its MailboxConcurrency limit while using the Microsoft Graph API this post may help you understand why. Background   The Mailbox  concurrency limit when your using the Graph API is 4 as per https://docs.microsoft.com/en-us/graph/throttling#outlook-service-limits . This is evaluated for each app ID and mailbox combination so this means you can have different apps running under the same credentials and the poor behavior of one won't cause the other to be throttled. If you compared that to EWS you could have up to 27 concurrent connections but they are shared across all apps on a first come first served basis. Batching Batching in the Graph API is a way of combining multiple requests into a single HTTP request. Batching in the Exchange Mail API's EWS and MAPI has been around for a long time and its common, for email Apps to process large numbers of smaller items for a variety of reasons.  Batching in the Graph is limited to a m

How to test SMTP using Opportunistic TLS with Powershell and grab the public certificate a SMTP server is using

Most email services these day employ Opportunistic TLS when trying to send Messages which means that wherever possible the Messages will be encrypted rather then the plain text legacy of SMTP.  This method was defined in RFC 3207 "SMTP Service Extension for Secure SMTP over Transport Layer Security" and  there's a quite a good explanation of Opportunistic TLS on Wikipedia  https://en.wikipedia.org/wiki/Opportunistic_TLS .  This is used for both Server to Server (eg MTA to MTA) and Client to server (Eg a Message client like Outlook which acts as a MSA) the later being generally Authenticated. Basically it allows you to have a normal plain text SMTP conversation that is then upgraded to TLS using the STARTTLS verb. Not all servers will support this verb so if its not supported then a message is just sent as Plain text. TLS relies on PKI certificates and the administrative issue s that come around certificate management like expired certificates which is why I wrote th
All sample scripts and source code is provided by for illustrative purposes only. All examples are untested in different environments and therefore, I cannot guarantee or imply reliability, serviceability, or function of these programs.

All code contained herein is provided to you "AS IS" without any warranties of any kind. The implied warranties of non-infringement, merchantability and fitness for a particular purpose are expressly disclaimed.