Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save FH-Inway/cbd0e0fea95a50311bb92540ef94b6e8 to your computer and use it in GitHub Desktop.
Save FH-Inway/cbd0e0fea95a50311bb92540ef94b6e8 to your computer and use it in GitHub Desktop.
LCS Authentication d365fo.tools style
# For debugging purposes, this script simulates how a call to [Get-D365LcsApiToken](https://github.com/d365collaborative/d365fo.tools/blob/development/d365fo.tools/functions/get-d365lcsapitoken.ps1)
# would execute the Invoke-RestMethod call.
# This script uses code from https://github.com/d365collaborative/PSOAuthHelper by @Splaxi
function Convert-HashToArgStringSwitch {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")]
[CmdletBinding()]
[OutputType([System.String])]
param (
[HashTable] $InputObject,
[string] $KeyPrefix = "-",
[string] $ValuePrefix = ":",
[switch] $KeepCase = $true
)
foreach ($key in $InputObject.Keys) {
$value = "{0}" -f $InputObject.Item($key).ToString()
if (-not $KeepCase) { $value = $value.ToLower() }
"$KeyPrefix$($key)$ValuePrefix$($value)"
}
}
# TODO Provide your own values for client_id, username and password
# client_secret should not be necessary if the app registration has been configured to allow public client flows
$parms = @{}
$parms.grant_type = "password"
$parms.resource = "https://lcsapi.lcs.dynamics.com"
$parms.client_id = "9b4f4503-b970-4ade-abc6-2c086e4c4929"
# $parms.client_secret = "s3cR3t"
$parms.username = "serviceaccount@domain.com"
$parms.password = "TopSecretPassword"
$parms.scope = "openid"
$body = (Convert-HashToArgStringSwitch -InputObject $parms -KeyPrefix "&" -ValuePrefix "=") -join ""
$body = $body.Substring(1)
$requestParams = @{Method = "Post"; ContentType = "application/x-www-form-urlencoded"; Body = $body}
$AuthProviderUri = "https://login.microsoftonline.com/common/oauth2/token"
try
{
$Authorization = Invoke-RestMethod $AuthProviderUri @requestParams
$Authorization
}
catch {
$PSItem
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment