gpt4 book ai didi

azure - 在需要 Azure 身份验证的应用程序上调用 RestMethod

转载 作者:行者123 更新时间:2023-12-02 23:44:14 28 4
gpt4 key购买 nike

如何使用 Powershell 调用 Azure 身份验证背后的 API?更具体地说,我确实希望这条线能够工作:Invoke-RestMethod -Method Get -Uri 'https://contoso.com/api/Hello

我的 API 是本地部署的(但在 Web 上可见),并且配置了 Azure AD 身份验证并且是强制的。

我希望以编程方式通过 Powershell 进行身份验证,这样我就可以调用 API,而无需任何额外的交互。

目前,无论我做什么,我在执行 Invoke-RestMethod 时都会遇到 401 错误。

关于 API

我正在使用通过 Visual Studio 创建的示例 asp.net core c# 应用程序(使用工作或学校身份验证方法)。此过程在 Azure 中创建了应用程序注册,并且我在 Azure 中手动创建了客户端 key 。

我尝试了什么

现在,使用 Powershell,我填写了以下内容

$Params = @{
'client_id' = ''
'Redirect_URI' = ''
'TenantID' = ''
'response_type'='code'

}
$ClientSecret = ''

从那里,我确实使用以下方式获得了授权码:

$Query = "?"; $Params.Keys | % {$Query+= "$($_)=$($Params.Item($_))&"} ; $Query = $Query.TrimEnd('&')


$IE= new-object -ComObject "InternetExplorer.Application"
$IE.Visible = $true
$IE.navigate2("https://login.microsoftonline.com/$($params.TenantID)/oauth2/authorize$Query")
Write-Host 'Press enter when Code is displayed in URL'

pause
$Code = [System.Web.HttpUtility]::ParseQueryString(([uri]$ie.LocationURL).Query)['code']
$ie.quit()

最后,我使用以下内容获取访问 token :

$TokenResult = Invoke-RestMethod -Method Post -ContentType 'application/x-www-form-urlencoded' -Uri "https://login.microsoftonline.com/$($Params.TenantID)/oauth2/v2.0/token" -Body @{
client_id = $Params.client_id
scope = 'User.Read offline_access'
code = $Code
redirect_uri = $Params.Redirect_URI
grant_type = 'authorization_code'
client_secret = $ClientSecret
}

但是,如果我现在尝试使用以下方式调用我的 API:

Invoke-RestMethod 'https://SomeDomain.com/api/values' -Headers @{Authorization = "Bearer $($TokenResult.access_token)"}

结果

我确实收到了未经授权的401

我的观察

我相信我成功地使用了以下方法与 Graph API 和其他 Azure API 进行交互。但是,当调用我自己的 Azure 身份验证背后的 API 时,这不起作用。

我应该如何进行正确的调用,以允许我使用 Azure 身份验证针对我的私有(private) API 进行身份验证?

最佳答案

我想您尚未在 AAD 中配置 API。要通过 AD 应用程序访问 api,您还需要在门户中为您的 api 创建 AD 应用程序,请参阅:Register an app with the Azure Active Directory v2.0 endpoint.并将其配置为公开 API,请参阅:Configure an application to expose web APIs (Preview)Configure a client application to access web APIs (Preview) 。然后您将能够调用 Graph API、Office 365 API 等 api。

You can develop a web API and make it available to client applications by exposing permissions/scopes and roles. A correctly configured web API is made available just like the other Microsoft web APIs, including the Graph API and the Office 365 APIs.

关于azure - 在需要 Azure 身份验证的应用程序上调用 RestMethod,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54997626/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com