azure - 访问 IIS 托管的 Web 应用程序,该应用程序通过 PowerShell 使用 AzureAD 凭据来使用 API

标签 azure powershell azure-active-directory openid-connect microsoft-identity-platform

我有一个 IIS 托管的 blazor 服务器 .net core Web 应用程序,它使用 AzureAd 登录,并且我的应用程序具有一些我想要向 API 公开的功能,并且我正在尝试运行一个 PowerShell 脚本来访问我的 Web 应用程序以运行方法。

但是,我遇到了登录问题,似乎无法登录我的应用程序。

这是我的 Web 应用程序 appsettings.json,当前在访问 https://localhost:8080/时可以正常工作并登录,该应用程序连接到我的应用程序的 Azure 应用程序注册。

 "AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "mycompanyname.onmicrosoft.com",
"TenantId": "redacted",
"ClientId": "redacted",
"ClientSecret": "redacted",
"ClientCertificates": [
], 
"CallbackPath": "/signin-oidc"
 },

尝试通过 PowerShell 连接时, 使用以下方法时我能够收到 access_token:

$tenantid = "<tenantid>"    
$clientId = "<clientid>"    
$ClientSecret = "<clientsecret>"

$Resource = "<resourceid>"

$RequestAccessTokenUri = "https://login.microsoftonline.com/$tenantid/oauth2/token"

$body = "grant_type=client_credentials&client_id=$clientId&client_secret=$ClientSecret&resource=$Resource"

$Token = Invoke-RestMethod -Method Post -Uri $RequestAccessTokenUri -Body $body -ContentType 'application/x-www-form-urlencoded'

我的问题是,我似乎无法找到如何使用此 access_token 来传递到我的网站进行登录,除非我不完全了解 Microsoft 如何进行身份验证和授权。

我已经解决这个问题几天了,需要帮助。

感谢任何帮助

最佳答案

要传递 token ,您需要构建一个授权 header 并将其传递给后续调用。

# Build header from access token
$Headers = @{Headers = @{Authorization = "Bearer $($token.Access_token)" } }

# Splat Headers onto any calls that require you to be authenticated.
Invoke-RestMethod -Uri 'Https://YourApp.com/Something' -Method Get @Headers

附加说明:

如果尚未存在,您将需要授权 Powershell 客户端 ID 才能使用应用注册。

这可以在您的应用程序注册中完成。

  • 转到公开 API
  • 添加 User_Impersonation 范围
  • 添加以下客户端应用:1950a258-227b-4e31-a9cf-717495945fc2

App registration

关于azure - 访问 IIS 托管的 Web 应用程序,该应用程序通过 PowerShell 使用 AzureAD 凭据来使用 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65604054/

相关文章:

Powershell线程处理问题

powershell - Windows 10 PowerShell Get-WindowsCapability 和 Add-WindowsCapability 命令出错

powershell - 为什么 PowerShell 拆分包含连字符和句点的参数?

azure - 如何将 AzureAD 应用程序限制在单个位置

azure - 权限不足,无法完成操作 - Azure Active Directory

python - 无法在 Windows 上通过 Python 生成 azure TTS

Azure 流量管理器确保禁用终结点后没有流量流动

azure - 作为个人开发人员的 Microsoft Multi-Tenancy 应用程序 - Azure Active Directory

azure - Azure 媒体服务的托管服务标识 (MSI)

powershell - 如何获取 Azure VM 的公共(public) IP?