Public/Connect-MsftIamApi.ps1

Function Connect-MsftIamApi {
    <#
        .SYNOPSIS
        Authenticates the end user to the Microsoft IAM Api.
 
        .DESCRIPTION
        Current version is focused on user authentication to the IAM Api.
        I have not yet successfully authenticated a service principal.
 
        .PARAMETER TenantId
        Takes in the tenant ID for the target azure tenant.
 
        .INPUTS
        None.
 
        .LINK
        https://github.com/nouselesstech/MsftIamApi
    #>


    param(
        [Parameter(Mandatory=$True)]
        [string]$TenantId,

        [Parameter(Mandatory=$True)]
        [string]$UserName,

        [Parameter(Mandatory=$True)]
        [string]$Password
    )

    try {
        # Variables
        $ApplicationId  = '1950a258-227b-4e31-a9cf-717495945fc2'

        ## Prepare the request information
        $Headers = @{}
        $Headers."Content-Type" = "application/x-www-form-urlencoded"

        $Body = "resource=74658136-14ec-4630-ad9b-26e160ff0fc6"
        $Body += "&client_id=$ApplicationId"
        $Body += "&username=$UserName"
        $Body += "&password=$([System.Web.HttpUtility]::UrlEncode($Password))"
        $Body += "&grant_type=password"

        $Url = "https://login.microsoftonline.com/$TenantId/oauth2/token"

        ## Complete the request
        $TokenResponse = Invoke-WebRequest `
            -Method Post `
            -Uri $Url `
            -Headers $Headers `
            -Body $Body 

        return $TokenResponse.Content | ConvertFrom-Json -Depth 100
    } catch {
        Write-Error "Unable to connect to the IAM API. `r`n $_"
    }
}