Set Intune as MDM Authority with PowerShell and Microsoft Graph API

Set Intune as MDM Authority with PowerShell and Microsoft Graph API

Before we can start to use Intune we have to set it as MDM Authority.
To automate this we can use PowerShell and Microsoft Graph API.

Like all other Graph API scripts we start by authenticating us to get a token we have to send in the header of the REST requests we send to Graph.
https://developer.microsoft.com/en-us/graph/docs/concepts/auth_overview

We then have to get our Intune Organizations ID. For this we use GET https://graph.microsoft.com/v1.0/organization”
https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/intune_onboarding_organization_get

We can check if Intune already is set with a GET request
https://graph.microsoft.com/beta/organization(‘$OrgId’)?`$select=mobiledevicemanagementauthority

When we have recorded the ID we can send the Graph API request POST https://graph.microsoft.com/v1.0/organization/$OrgID/setMobileDeviceManagementAuthority
https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/intune_onboarding_organization_setmobiledevicemanagementauthority

Function Get-AuthToken {

<#
Authenticate against Intune tenant
#>

[cmdletbinding()]

param
(
    [Parameter(Mandatory=$true)]
    $User
)

$userUpn = New-Object "System.Net.Mail.MailAddress" -ArgumentList $User

$tenant = $userUpn.Host

Write-Host "Looking for AzureAD module..."

    $AadModule = Get-Module -Name "AzureAD" -ListAvailable

    if ($AadModule -eq $null) {

        Write-Host "AzureAD PowerShell not found, look for AzureADPreview"
        $AadModule = Get-Module -Name "AzureADPreview" -ListAvailable

    }

    if ($AadModule -eq $null) {
        write-host
        write-host "AzureAD Powershell module not installed..." -f Red
        write-host "Install by running 'Install-Module AzureAD' eller 'Install-Module AzureADPreview' fra en elevert PowerShell-prompt" -f Yellow
        write-host "Script can not continue..." -f Red
        write-host
        exit
    }

# Getting path to ActiveDirectory Assemblies
# If the module count is greater than 1 find the latest version

    if($AadModule.count -gt 1){

        $Latest_Version = ($AadModule | select version | Sort-Object)[-1]

        $aadModule = $AadModule | ? { $_.version -eq $Latest_Version.version }

            # Checking if there are multiple versions of the same module found

            if($AadModule.count -gt 1){

            $aadModule = $AadModule | select -Unique

            }

        $adal = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
        $adalforms = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll"

    }

    else {

        $adal = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
        $adalforms = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll"

    }

[System.Reflection.Assembly]::LoadFrom($adal) | Out-Null

[System.Reflection.Assembly]::LoadFrom($adalforms) | Out-Null

$clientId = "d1ddf0e4-d672-4dae-b554-9d5bdfd93547"

$redirectUri = "urn:ietf:wg:oauth:2.0:oob"

$resourceAppIdURI = "https://graph.microsoft.com"

$authority = "https://login.microsoftonline.com/$Tenant"

    try {

    $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority

    # https://msdn.microsoft.com/en-us/library/azure/microsoft.identitymodel.clients.activedirectory.promptbehavior.aspx
    # Change the prompt behaviour to force credentials each time: Auto, Always, Never, RefreshSession

    $platformParameters = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters" -ArgumentList "Auto"

    $userId = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier" -ArgumentList ($User, "OptionalDisplayableId")

    $authResult = $authContext.AcquireTokenAsync($resourceAppIdURI,$clientId,$redirectUri,$platformParameters,$userId).Result

        # If the accesstoken is valid then create the authentication header

        if($authResult.AccessToken){

        # Creating header for Authorization token

        $authHeader = @{
            'Content-Type'='application/json'
            'Authorization'="Bearer " + $authResult.AccessToken
            'ExpiresOn'=$authResult.ExpiresOn
            }

        return $authHeader

        }

        else {

        Write-Host
        Write-Host "Authorization Access Token is null, please re-run authentication..." -ForegroundColor Red
        Write-Host
        break

        }

    }

    catch {

    write-host $_.Exception.Message -f Red
    write-host $_.Exception.ItemName -f Red
    write-host
    break

    }

}

Function Get-OrgID(){

<#
Finner Organization ID
#>

[cmdletbinding()]

$graphApiVersion = "v1.0"
$emptybody = @"
{
}
"@

try {

        $Resource = "organization"
        $uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)"
        $GroupsResponse = (Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get).value
        $OrgID = $GroupsResponse.id
        return $OrgID 

     }

    catch {

    Write-Host
    $ex = $_.Exception
    $errorResponse = $ex.Response.GetResponseStream()
    $reader = New-Object System.IO.StreamReader($errorResponse)
    $reader.BaseStream.Position = 0
    $reader.DiscardBufferedData()
    $responseBody = $reader.ReadToEnd();
    Write-Host "Response content:`n$responseBody" -f Red
    Write-Error "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)"
    write-host
    break

    }

}

Function Update-MDMAuth(){

<#
Setting Mobile Device Device Management Authority to Intune
#>

[cmdletbinding()]

param
(
    $OrgID
)

$graphApiVersion = "v1.0"
$Resource = "/organization/$OrgID/setMobileDeviceManagementAuthority"
$JSON = @"
{
    
}
"@

    try {
$url = "https://graph.microsoft.com/beta/organization('$OrgId')?`$select=mobiledevicemanagementauthority"
$MDMAuthority = (Invoke-RestMethod -Uri $url -Headers $authToken -Method Get).mobileDeviceManagementAuthority

if($MDMAuthority -notlike "intune")
{
        $uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)"
        Invoke-RestMethod -Uri $uri -Headers $authToken -Method Post -Body $JSON -ContentType "application/json"
 }   
        }

    catch {

    Write-Host
    $ex = $_.Exception
    $errorResponse = $ex.Response.GetResponseStream()
    $reader = New-Object System.IO.StreamReader($errorResponse)
    $reader.BaseStream.Position = 0
    $reader.DiscardBufferedData()
    $responseBody = $reader.ReadToEnd();
    Write-Host "Response content:`n$responseBody" -f Red
    Write-Error "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)"
    write-host

    }

}

#region Authentication

write-host

# Checking if authToken exists before running authentication
if($global:authToken){

    # Setting DateTime to Universal time to work in all timezones
    $DateTime = (Get-Date).ToUniversalTime()

    # If the authToken exists checking when it expires
    $TokenExpires = ($authToken.ExpiresOn.datetime - $DateTime).Minutes

        if($TokenExpires -le 0){

        write-host "Authentication Token expired" $TokenExpires "minutes ago" -ForegroundColor Yellow
        write-host

            # Defining User Principal Name if not present

            if($User -eq $null -or $User -eq ""){

            $User = Read-Host -Prompt "Please specify your user principal name for Azure Authentication"
            Write-Host

            }

        $global:authToken = Get-AuthToken -User $User

        }
}

# Authentication doesn't exist, calling Get-AuthToken function

else {

    if($User -eq $null -or $User -eq ""){

    $User = Read-Host -Prompt "Intune admin username"
    Write-Host

    }

# Getting the authorization token
$global:authToken = Get-AuthToken -User $User

}

#endregion

#Set Intune as MDM Authority
Update-MDMAuth -OrgID Get-OrgID

 

Microsoft.Graph.Intune

You could also do this with the new Microsoft.Graph.Intune Powershell Module.

First you install it with Install-Module Microsoft.Graph.Intune

You authenticate with Connect-MSGraph

#Connect to MS Graph API

Connect-MSGraph


#Check if Intune already is MDM Authority

$mdmAuth = (Invoke-MSGraphRequest -Url "https://graph.microsoft.com/beta/organization('$OrgId')?`$select=mobiledevicemanagementauthority" -HttpMethod Get -ErrorAction Stop).mobileDeviceManagementAuthority


#Sets Intune as MDM Authority if not already set

if($mdmAuth -notlike "intune")
{
    Write-Progress -Activity "Setter Intune som MDM Authority" -Status "..."
    $OrgID = (Invoke-MSGraphRequest -Url "https://graph.microsoft.com/v1.0/organization" -HttpMethod Get -ErrorAction Stop).value.id
    Invoke-MSGraphRequest -Url "https://graph.microsoft.com/v1.0/organization/$OrgID/setMobileDeviceManagementAuthority" -HttpMethod Post -ErrorAction Stop
}

 

By | 2019-06-07T08:48:34+01:00 April 8th, 2019|Graph API, Powershell|0 Comments

Leave A Comment