Azure管理API无法使用ADAL进行身份验证

时间:2018-09-05 13:29:13

标签: azure powershell azure-management-api

我正在寻找一种方法来停止在非办公时间向开发环境收费的Cloud Services。

我发现的资源表明,删除部署后,不再为Cloud服务计费。

我们想将已部署的云服务配置和程序包文件下载到blob位置,并删除部署以停止计费。当我们想再次使用它们时,我们想从Blob位置进行部署。我们要使用Powershell脚本来停止(下载和删除)并开始(重新部署备份)。

我发现了一些文章,解释了如何使用ADAL和Azure管理Rest API下载配置文件。

身份验证似乎是一个问题。当我执行脚本时:我收到错误消息: Invoke-RestMethod:禁止的错误服务器无法验证请求。验证证书有效并与此预订关联。 在线:78字符:25 + ... SourceKey = Invoke-RestMethod-方法POST -Headers $ requestheader -U ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~     + CategoryInfo:InvalidOperation:(System.Net.HttpWebRequest:HttpWebRequest)[Invoke-RestMethod],WebException     + FullyQualifiedErrorId:WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

我使用在Azure门户中具有我使用的订阅的贡献者权限的帐户登录。

####### RESOURCES #######
# 1. https://www.magnetismsolutions.com/blog/jaredjohnson/2014/11/10/download-microsoft-azure-cloud-service-package-files
# 2. https://docs.microsoft.com/en-us/previous-versions/azure/reference/jj154121(v%3dazure.100)
# 3. https://www.powershellgallery.com/packages/Microsoft.ADAL.PowerShell/1.12
# 4. https://blogs.technet.microsoft.com/keithmayer/2014/12/30/leveraging-the-azure-service-management-rest-api-with-azure-active-directory-and-powershell-list-azure-administrators/
# 5. https://www.powershellmagazine.com/2014/12/24/using-azure-resource-management-rest-api-in-powershell/
# 6. https://shawntabrizi.com/aad/azure-ad-authentication-with-powershell-and-adal/
# https://www.codeisahighway.com/how-to-easily-and-silently-obtain-accesstoken-bearer-from-an-existing-azure-powershell-session/
#####
# Error: The server failed to authenticate the request. Verify that the certificate is valid and is associated with this subscription.
#####
# https://github.com/Azure/azure-xplat-cli/issues/2040
# https://blogs.msdn.microsoft.com/goutham/2015/06/16/azure-powershell-forbiddenerror-the-server-failed-to-authenticate-the-request-verify-the-certificate-is-valid-and-is-associated-with-this-subscription/
# https://ulvbjornsson.com/2017/07/03/microsoft-azure-azure-powershell-forbiddenerror-the-server-failed-to-authenticate-the-request/
#########################


$Azure = Get-AzureRmEnvironment 'AzureCloud'
$Env = Login-AzureRmAccount -Environment $Azure -Verbose 
$Global:SubscriptionName = "SubscriptionName"

Set-AzureRmContext -Subscription $Global:SubscriptionName

Function RESTAPI-Auth 
{
    $Subscription = Get-AzureRmSubscription -SubscriptionName $Global:SubscriptionName

    # Load ADAL Azure AD Authentication Library Assemblies
    $adal = "C:\Git\Spike\Microsoft.ADAL.PowerShell\2.28\Microsoft.IdentityModel.Clients.ActiveDirectory.dll" 
    $adalforms = "C:\Git\Spike\Microsoft.ADAL.PowerShell\2.28\Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms.dll" 
    [System.Reflection.Assembly]::LoadFrom($adal)
    [System.Reflection.Assembly]::LoadFrom($adalforms)

    $adTenant = $Subscription.TenantId
    $global:SubscriptionID = $Subscription.SubscriptionId

    # Set well-known client ID for Azure PowerShell
    $clientId = "1950a258-227b-4e31-a9cf-717495945fc2"

    # Set redirect URI for Azure PowerShell
    $redirectUri = "urn:ietf:wg:oauth:2.0:oob"

    # Set Resource URI to Azure Service Management API
    $resourceAppIdURI = "https://management.core.windows.net/"

    # Authenticate and Acquire Token

    # Set Authority to Azure AD Tenant
    $authority = "https://login.windows.net/$adTenant"

    # Create Authentication Context tied to Azure AD Tenant
    $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority

    # Acquire token
    $global:authResult = $authContext.AcquireToken($resourceAppIdURI, $clientId, $redirectUri, "Auto")
}

#https://docs.microsoft.com/en-us/previous-versions/azure/reference/jj154121(v%3dazure.100)
Function GetAuditingServicePackage() 
{ 
    $Subscription = Get-AzureRmSubscription -SubscriptionName $Global:SubscriptionName

    # Create Authorization Header
    $authHeader = $global:authResult.CreateAuthorizationHeader()

    # Set HTTP request headers to include Authorization header
    $requestHeader = @{
        "x-ms-version" = "2012-03-01"; 
        "ContentLength"= "0";
        "Authorization" = $authHeader
    }

    $CloudServiceName = "CloudServiceName"
    $DeploymentId = "DeploymentIdCopiedFromTheAzurePortal" 
    $TempBlobStorageContainerUri = "TheBlobLocationUri"

    $Uri = "Https://management.core.windows.net/$Subscription.SubscriptionId/services/hostedservices/$CloudServiceName/deployments/$DeploymentId/package?containerUri=$TempBlobStorageContainerUri"
    $Global:SourceKey = Invoke-RestMethod -Method POST -Headers $requestheader -Uri $Uri 
}



RESTAPI-Auth
$global:authResult

##########################################################################################
#######################      Rest API against Azure Classic     ##########################
##########################################################################################
GetAuditingServicePackage

在输出窗口中,我看到获得了Bearer访问令牌。我向Fiddler验证了,向管理API发出请求时,此令牌已添加到标头中。

有人可以解释为什么我遇到此错误并提供解决方案吗?

谢谢, 马克

1 个答案:

答案 0 :(得分:0)

尝试清除您的Azure配置文件

Clear-AzureProfile

更多细节可用here