簡體   English   中英

如何以編程方式獲取 Azure API 管理的訪問令牌?

[英]How to get the access token to Azure API Management programmatically?

我正在嘗試通過將 OAuth 2.0 與 Azure Active Directory 和 API 管理文檔結合使用,使用 Protect an API在我的 API 管理實例中實現 Azure Active Directory。 該文檔建議,為了獲得訪問令牌,我需要使用開發人員門戶。

我的問題是:外部應用程序將與 API 管理進行通信。 有沒有辦法省略開發人員門戶並以編程方式獲取訪問令牌?

這很痛苦,但多虧了 Jos Lieben,我才能夠用這個 Powershell 功能做到這一點

它專門用於代表組織授予 API 訪問權限,但正如您所見,您可以提取命令來獲取和使用 API 令牌。

原作者鏈接: https : //www.lieben.nu/liebensraum/2018/04/how-to-grant-oauth2-permissions-to-an-azure-ad-application-using-powershell-unattended-silently/

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM