簡體   English   中英

如何使用客戶端密碼通過 Powershell 訪問 Azure WebApp

[英]How to access Azure WebApp via Powershell using client secret

我在 Azure 中創建了一個啟用了 Azure 身份驗證的 WebApp。 這在使用用戶進行身份驗證時按預期工作。 但是 WebApp 有一個特定的端點,除了發布 JSON 數據之外,它可以被解析並表示為圖表。 我想做的是發布這些由眾多 Powershell 腳本收集的數據。 如果我在用戶帳戶的上下文中運行 Powershell 腳本,我可以做到這一點,但我想使用 SPN 進行身份驗證(因此使用應用程序 ID 和已設置的密鑰)。 這甚至可能嗎? 我已經嘗試了下面的代碼,它實際上確實獲得了訪問令牌,但是在發布請求的標頭中發送它時,我得到了一個

“您無權查看此目錄或頁面。”

錯誤信息。

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

$ClientId = "Application Id"

$ClientSecret = "Client Secret"

$Resource = "URL of the WebApp"

$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'

$Headers = @{}

$Headers.Add("Authorization","$($Token.token_type) $($Token.access_token)")

$AppUri = $Resource + "/upload/post"
$json = <This will contain the actual JSON objects that will be posted>

invoke-RestMethod -Uri $AppUri -Method Post -Headers $Headers -body $json

通過使用 SPN 進行身份驗證,是否甚至可以從 Powershell 訪問 Azure WebApp? 任何幫助都感激不盡。

通過使用 SPN 進行身份驗證,是否甚至可以從 Powershell 訪問 Azure WebApp?

對的,這是可能的。 但是我們需要使用會話令牌(而不是訪問令牌)來訪問應用程序資源。

使用訪問令牌獲取authenticationToken

要求:

POST https://<appname>.azurewebsites.net/.auth/login/aad HTTP/1.1
Content-Type: application/json

{"id_token":"<token>","access_token":"<token>"}

回復:

{
    "authenticationToken": "...",
    "user": {
        "userId": "sid:..."
    }
}

獲得此會話令牌后,您可以通過將X-ZUMO-AUTH標頭添加到 HTTP 請求來訪問受保護的應用程序資源

GET https://<appname>.azurewebsites.net/api/products/1
X-ZUMO-AUTH: <authenticationToken_value>

這是有效的 powershell 腳本。

$RequestAccessTokenUri = "https://login.microsoftonline.com/{tenantId}/oauth2/token"

$ClientId = "{Application Id}"

$ClientSecret = "{client secret}"

$Resource = "{Application Id}"

$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'
#get authentication token url
$RequestAuthenticationTokenUri="https://webapi-productsapp2093.azurewebsites.net/.auth/login/aad"

$bodystr = "{" + '"' + "access_token" + '"' + ":"  +  '"' +      $Token.access_token +  '"' + "}"

$authenticationToken=Invoke-RestMethod -Method Post -Uri $RequestAuthenticationTokenUri -Body $bodystr -ContentType 'application/json'

$Headers = @{}
$Headers.Add("X-ZUMO-AUTH",$authenticationToken.authenticationToken)

$website="http://webapi-productsapp2093.azurewebsites.net/api/products/1"
invoke-RestMethod -Uri $website -Method Get -Headers $Headers

參考:

驗證來自提供商的令牌

暫無
暫無

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

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