Skip to content

Instantly share code, notes, and snippets.

@kevinblumenfeld
Created November 24, 2021 19:44
Show Gist options
  • Save kevinblumenfeld/3317bcae617da54c781e5849bccf1b99 to your computer and use it in GitHub Desktop.
Save kevinblumenfeld/3317bcae617da54c781e5849bccf1b99 to your computer and use it in GitHub Desktop.
function Connect-Graph {
<#
.SYNOPSIS
Connect to Graph with delegate or application only permissions
.DESCRIPTION
Connect to Graph with delegate or application only permissions
.PARAMETER Tenant
** Use NameOfTenant if the tenant domain is NameOfTenant.onmicrosoft.com **
** do NOT use the entire domain, just NameOfTenant **
.PARAMETER Workload
This must be exactly what you specified during Add-GraphConfig
.PARAMETER Delegated
Use this switch only if you did added a username and password when using the GUI, Add-GraphConfig
.EXAMPLE
Connect-Graph -Tenant NameOfTenant -Workload DEMO
NOTE: use NameOfTenant if the tenant domain is NameOfTenant.onmicrosoft.com
don't use the entire domain, just NameOfTenant
.EXAMPLE
Connect-Graph -Tenant NameOfTenant -Workload DEMO -Delegated
NOTE: use NameOfTenant if the tenant domain is NameOfTenant.onmicrosoft.com
don't use the entire domain, just NameOfTenant
.NOTES
Prior to running this command, you will need to run Add-GraphConfig
NOTE: Running Add-GraphConfig is a one time thing (per app registration).
For example:
Add-GraphConfig -Tenant NameOfTenant -Workload DEMO
#>
[CmdletBinding()]
param (
[Parameter(Mandatory)]
$Tenant,
[Parameter(Mandatory)]
[string]
$Workload,
[Parameter()]
[switch]
$Delegated
)
$Script:Tenant = $Tenant
$Script:Workload = $Workload
$Script:Delegated = $Delegated
$Script:Path = "$env:USERPROFILE\.GraphTools\Tenants\$Tenant\$Workload"
$host.ui.RawUI.WindowTitle = ('{0} ({1})' -f $Tenant, $Workload)
$Script:Config = Import-Clixml "$Path\Config.xml"
if ($Delegated) {
$Script:Cred = Import-Clixml "$Path\Cred.xml"
$Request = @{
Method = 'POST'
Body = @{
Grant_Type = 'PASSWORD'
Client_Id = $Script:Config.ClientId
Client_Secret = $Script:Config.cred.GetNetworkCredential().password
Username = $Script:cred.UserName
Password = $Script:cred.GetNetworkCredential().password
Scope = "offline_access https://graph.microsoft.com/.default"
}
Uri = "https://login.microsoftonline.com/$Script:Tenant.onmicrosoft.com/oauth2/v2.0/token"
}
}
else {
$Request = @{
Method = 'POST'
Body = @{
Grant_Type = 'client_credentials'
Client_Id = $Script:Config.ClientId
Client_Secret = $Script:Config.cred.GetNetworkCredential().password
Scope = "https://graph.microsoft.com/.default"
}
Uri = "https://login.microsoftonline.com/$Script:Tenant.onmicrosoft.com/oauth2/v2.0/token"
}
}
$Response = Invoke-RestMethod @Request
$Script:RefreshTime = ([datetime]::UtcNow).AddSeconds($Response.expires_in - 10)
$Script:Token = $Response.access_token
$Script:RefreshToken = $Response.refresh_token
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment