Luk*_*por 4 authentication rest powershell azure
我需要获取访问令牌以使用 REST API访问 Azure(https://management.azure.com端点)中的资源。读过的每篇文章,都在用 Appliction Id 计算。就我而言,Azure 租户刚刚(以编程方式)创建,我必须在其中创建一些资源。
我唯一拥有的是租户 ID、订阅 ID、管理员帐户的用户名和密码。如何仅使用我拥有的信息进行身份验证?它如何在 PowerShell 中工作,不需要使用应用程序 ID?
据我所知,这是不可能的。正如junnas所说,即使您使用用户/密码身份验证,也需要客户端ID。
在 Azure 上创建服务主体很容易,您可以查看此链接。
sp创建后,你会得到客户端id,客户端密码。您还需要Owner在订阅时赋予 sp角色,您可以查看此链接。
例如,现在您可以使用 sp 在 Power Shell 中调用 rest api。
##get token
$TENANTID=""
$APPID=""
$PASSWORD=""
$result=Invoke-RestMethod -Uri https://login.microsoftonline.com/$TENANTID/oauth2/token?api-version=1.0 -Method Post -Body @{"grant_type" = "client_credentials"; "resource" = "https://management.core.windows.net/"; "client_id" = "$APPID"; "client_secret" = "$PASSWORD" }
$token=$result.access_token
##set subscriptionId and resource group name
$subscriptionId=""
$resourcegroupname="shui5"
$Headers=@{
'authorization'="Bearer $token"
'host'="management.azure.com"
'contentype'='application/json'
}
$body='{
"location": "northeurope",
"tags": {
"tagname1": "test-tag"
}
}'
Invoke-RestMethod -Uri "https://management.azure.com/subscriptions/$subscriptionId/resourcegroups/${resourcegroupname}?api-version=2015-01-01" -Headers $Headers -Method PUT -Body $body
Run Code Online (Sandbox Code Playgroud)
您可以使用 Microsoft PowerShell 应用程序 ID 进行身份验证,而无需拥有自己的应用程序 ID。此代码片段将为您提供令牌:
Import-Module MSOnline # IMPORTANT! Loads type assembly Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext
$TENANTID = "" # Your Tenant ID
$clientId = "1b730954-1685-4b74-9bfd-dac224a7b894" # PowerShell Client Id
$MSMgmtURI = "https://management.core.windows.net"
$authority = "https://login.microsoftonline.com/$TENANTID"
$redirectUri = "urn:ietf:wg:oauth:2.0:oob"
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
$authResult = $authContext.AcquireToken($MSMgmtURI, $clientId, $redirectUri, "Always")
$token = $authResult.AccessToken
$headers = @{'Authorization' = "Bearer $token", 'host'="management.azure.com", 'Content-Type' = "application/json"}
Run Code Online (Sandbox Code Playgroud)
这对于使用登录对话框获取访问令牌很有用。我怀疑 PowerShell 的客户端 ID 可以在上面的 Oath2 调用中使用。
| 归档时间: |
|
| 查看次数: |
5756 次 |
| 最近记录: |