如何以编程方式获取对Azure API Management的访问令牌?

问题描述 投票:0回答:1

我正在尝试使用Protect an API by using OAuth 2.0 with Azure Active Directory and API Management文档在我的API管理实例中实现Azure Active Directory。该文档建议,为了获取访问令牌,我需要使用Developer Portal。

我的问题是:外部应用程序将与API Management通信。有没有办法忽略开发人员门户并以编程方式获取访问令牌?

azure azure-active-directory azure-api-management
1个回答
1
投票

这很痛苦,但要感谢Jos Lieben,我可以使用此Powershell功能来做到这一点

专门用于代表组织授予API访问权限,但是如您所见,您可以提取命令以获取和使用API​​令牌。

Function Grant-OAuth2PermissionsToApp{
    Param(
        [Parameter(Mandatory=$true)]$Username, #global administrator username
        [Parameter(Mandatory=$true)]$Password, #global administrator password
        [Parameter(Mandatory=$true)]$azureAppId #application ID of the azure application you wish to admin-consent to
    )

    $secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
    $mycreds = New-Object System.Management.Automation.PSCredential ($Username, $secpasswd)
    $res = login-azurermaccount -Credential $mycreds
    $context = Get-AzureRmContext
    $tenantId = $context.Tenant.Id
    $refreshToken = @($context.TokenCache.ReadItems() | where {$_.tenantId -eq $tenantId -and $_.ExpiresOn -gt (Get-Date)})[0].RefreshToken
    $body = "grant_type=refresh_token&refresh_token=$($refreshToken)&resource=74658136-14ec-4630-ad9b-26e160ff0fc6"
    $apiToken = Invoke-RestMethod "https://login.windows.net/$tenantId/oauth2/token" -Method POST -Body $body -ContentType 'application/x-www-form-urlencoded'
    $header = @{
     'Authorization' = 'Bearer ' + $apiToken.access_token
     'X-Requested-With'= 'XMLHttpRequest'
     'x-ms-client-request-id'= [guid]::NewGuid()
     'x-ms-correlation-id' = [guid]::NewGuid()
    }
    $script:url = "https://main.iam.ad.ext.azure.com/api/RegisteredApplications/$azureAppId/Consent?onBehalfOfAll=true"
    Invoke-RestMethod -Uri $url -Headers $header -Method POST -ErrorAction Stop
}
© www.soinside.com 2019 - 2024. All rights reserved.