beadaman
beadaman

Reputation: 93

Using Graph API with password grant type for a federated ID with Powershell

I am trying to create a batch which changes users' MFA phone number in case it got screwed up and an unreachable phone number has been set.

The API does not support application permissions, so I am thinking of using password grant type and implementing the encrypted ID and password of the Administrator. I know this is far from optimal, but I just don't see any other way.

Here is the code I use.

$ReqTokenBody = @{
  Grant_Type    = "Password"
  Client_Id     = $clientID
  Client_Secret = $clientSecret
  Username      = $privilegedAuthenticationManager
  Password      = $password
  Scope         = "https://graph.microsoft.com/.default"
}

$TokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" -Method POST -Body $ReqTokenBody

The problem that I am facing, is that this is only supported with managed IDs (not synced from ADs), and I would really like to use federated IDs as that is company policy.

Is there a way to do this in powershell? If not, in C# maybe?

Any help is greatly appreciated. Thank you.

Upvotes: 0

Views: 1784

Answers (1)

Glen Scales
Glen Scales

Reputation: 22032

If your use the MSAL or ADAL library it will handle the federation authentication for you (eg does WSTrust SOAP post against your ADFS server's active endpoint). There are modules for both MSAL and ADAL in the powershell gallery eg https://www.powershellgallery.com/packages/MSAL.PS/4.2.1.3

The code to use it is directly yourself is pretty simple though for ADAL

Import-Module .\Microsoft.IdentityModel.Clients.ActiveDirectory.dll -Force
$ClientId = "5471030d-f311-4c5d-91ef-74ca885463a7"

$Credentials = get-credential
$domain = $Credentials.UserName.ToString().Split('@')[1]

$TenantId = (Invoke-WebRequest https://login.windows.net/$domain/v2.0/.well-known/openid-configuration | ConvertFrom-Json).token_endpoint.Split('/')[3]

$ClientCredentials = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserPasswordCredential" -ArgumentList $Credentials.UserName.ToString(),$Credentials.GetNetworkCredential().password.ToString()
$Context = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext("https://login.microsoftonline.com/$TenantId")
return ([Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContextIntegratedAuthExtensions]::AcquireTokenAsync($Context,"https://graph.microsoft.com", $ClientId ,$ClientCredentials)).Result

Upvotes: 1

Related Questions