我正试图避免使用任何额外的电荷模块(5.1个单元),因此,我正在使用这一文字(用户Id,美元坚挺)。 I和cer是这一职位的随机值:
$thumbprint = "<thumbprint taken from the cert properties>"
$expUnixTime = [math]::truncate(((Get-Date).AddMinutes(30).ToUniversalTime()).Subtract((Get-Date "1970-01-01").ToUniversalTime()).TotalSeconds)
$payload = @{
iss = "CN=<issuer>"
sub = "CN=<subject (same as issuer)>"
aud = "https: //login.microsoftonline.com/<tenant name>.onmicrosoft.com/oauth2/v2.0/token"
exp = $expUnixTime # Token expiration time (30 minutes from now)
}
$encodedPayload = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes(($payload | ConvertTo-Json)))
$cert = Get-Item -Path Cert:CurrentUserMy$thumbprint
$rsaPrivateKey = $cert.PrivateKey
$rsaCryptoProvider = New-Object System.Security.Cryptography.RSACryptoServiceProvider
$rsaCryptoProvider.ImportParameters($rsaPrivateKey.ExportParameters("PKCS8"))
$signatureBytes = $rsaCryptoProvider.SignData([System.Text.Encoding]::UTF8.GetBytes($encodedPayload), "SHA256")
$encodedSignature = [Convert]::ToBase64String($signatureBytes)
$jwtAssertion = "$encodedPayload.$encodedSignature"
$clientId = "<client id guid>"
$tenantId = "<teant id guid>"
$tokenUrl = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
try {
$body = @{
client_id = $clientId
tenant_id = $tenantId
client_assertion_type = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
client_assertion = $jwtAssertion
scope = "https://graph.microsoft.com/.default"
grant_type = "client_credentials"
}
$bodyQueryString = $(Foreach ($item in $body.GetEnumerator()) {
"$($item.Key)=$($item.Value)"
}) -join &
$response = Invoke-RestMethod -Uri $tokenUrl -Method Post -Body $bodyQueryString -ContentType "application/x-www-form-urlencoded"
$response
} catch {
Write-Error "Error: $($_.Exception.Message)"
}
我正在回过这个错误:
{"error":"invalid_request","error_description":"AADSTS50027: JWT token is invalid or malformed. Trace ID: Correlation ID: Timestamp: 2024-02-20 20:50:49Z","error_codes":[50027],"timestamp":"2024-02-20 20:50:49Z","trace_id":"","correlation_id":"","error_uri":"https://login.microsoftonline.com/error?code=50027"}
I have looked at a few other questions, but have not identified anything helpful.