如何使用客户端机密通过Powershell访问Azure WebApp

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

我已在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的访问吗?任何帮助将不胜感激。

azure powershell authentication web-applications
1个回答
0
投票

甚至有可能获得从Powershell到Azure WebApp的访问权限通过使用SPN进行身份验证?

是的,有可能。但是我们需要使用会话令牌(非访问令牌)来访问应用程序资源。

用户访问令牌以获取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

参考:

Validate tokens from providers

© www.soinside.com 2019 - 2024. All rights reserved.