Hi @Rising Flight ,
Welcome to the Microsoft Q&A platform!
From your description, you are trying to authenticate in a PowerShell script using a client key stored in a file. The problem may be due to the way the secure string is converted back to a plain text string. Here is a revised version of the script that should work fine:
$ClientId = "9999999999999999999"
$ClientKeyPath = "c:\temp\myappreg.key"
$TenantId = "88888888888888888888888"
# Read the encrypted client secret from the file and convert it back to a secure string
$SecureString = Get-Content $ClientKeyPath | ConvertTo-SecureString
# Convert the secure string to plain text
$ClientSecret = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto(
[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString)
)
# Get an access token
$body = @{
grant_type = "client_credentials"
client_id = $ClientId
client_secret = $ClientSecret
scope = "https://outlook.office365.com/.default"
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$response = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token" -Method Post -ContentType "application/x-www-form-urlencoded" -Body $body
$accessToken = $response.access_token
# Load EWS Managed API (Exchange 2016)
$EWSServicePath = 'C:\Scripts\EWS-Managed-API\bin\Debug\Microsoft.Exchange.WebServices.dll'
Import-Module $EWSServicePath
# Connect to Exchange Online using EWS with OAuth
$ExchVer = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2016
$Service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchVer)
$Service.Url = "https://outlook.office365.com/EWS/Exchange.asmx"
$Service.Credentials = New-Object Microsoft.Exchange.WebServices.Data.OAuthCredentials($accessToken)
Make sure the file c:\temp\myappreg.key contains the encrypted client key. The script reads this file, converts the encrypted client key back to a secure string and then to plain text. This plain text client key is used to obtain an access token from Azure AD.
Please feel free to contact me for any updates. And if this helps, don't forget to mark it as an answer.
Best,
Jake Zhang