0
votes

I am looking for a way to stop our Cloud Services in the development environment being billed during out of office time.

The resources I found indicate that for a Cloud service stopped being billed when the deployment is removed.

We want to download the deployed cloud service configuration and package file to a blob location and remove the deployment to stop the billing. When we want to use them again, we want to deploy from the blob location. We want to use a Powershell script for stopping (downloading and removing) and for starting (re-deploying backup).

I found some articles explaining how to download the config an package file by using ADAL and the Azure management Rest API.

Authentication seems to be an issue. When I execute my script: I receive the error message: Invoke-RestMethod : Forbidden Error The server failed to authenticate the request. Verify that the certificate is valid and is associated with this subscription. At line:78 char:25 + ... SourceKey = Invoke-RestMethod -Method POST -Headers $requestheader -U ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

I login with an account that has contributor rights in the Azure portal for the subscription I use.

####### 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

In the output window I see an Bearer access token is obtained. I verified with Fiddler that this token was adder to the header when the request is made to the management API.

Can some one explain why I got this error and provide a solution how to solve it?

Thanks, Marc

1

1 Answers

0
votes

Try clearing your Azure Profile

Clear-AzureProfile

A little more details available here