Search code examples
c#asp.net-core.net-6.0azure-cdn

Getting AuthorizationFailed error while attempting to purge Azure CDN cache for particular content file


I am trying to generate a token and purge the Azure CDN cache for a particular content file. I am able to generate the token successfully but I am always getting below error

{"error":{"code":"AuthorizationFailed","message":"The client 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' with object id 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' does not have authorization to perform action 'Microsoft.Cdn/profiles/endpoints/purge/action' over scope '/subscriptions/yyyyyyyyyyyyyyyyyyyyyyyyyyyy/resourcegroups/NONPRD-SEA/providers/Microsoft.Cdn/profiles/devmaritimeinfoportal/endpoints/devmaritimeinfoportal' or the scope is invalid. If access was recently granted, please refresh your credentials."}}

When I try the same thing with from Try it editor here it is successfull.

Here is my code

        string clientId = ManagerConfig.AAD_ClientId;
        string clientSecret = ManagerConfig.AAD_ClientSecret;
        var authenticationContext = new AuthenticationContext("https://login.microsoftonline.com/"+ManagerConfig.AAD_TenantId);
        ClientCredential clientCredential = new ClientCredential(clientId, clientSecret);
        Task<AuthenticationResult> resultstr = authenticationContext.AcquireTokenAsync("https://management.core.windows.net/", clientCredential);

        string apiResponse = string.Empty;
        string bearerToken = resultstr.Result.AccessToken;
        string fileCachePurgeRequestUrl = "https://management.azure.com/subscriptions/yyyyyyyyyyyyyyyyyyyyyyyyyyyy/resourcegroups/NONPRD-SEA/providers/Microsoft.Cdn/profiles/devmaritimeinfoportal/endpoints/devmaritimeinfoportal/purge?api-version=2023-05-01";
        var RequestBody = new Dictionary<string, string[]>
        {
            {"contentPaths",filePaths}
        };
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
        var jsonData = JsonConvert.SerializeObject(RequestBody);
        var contentData = new StringContent(jsonData, Encoding.UTF8, "application/json");
        var response = await client.PostAsync(fileCachePurgeRequestUrl, contentData);
        apiResponse = await response.Content.ReadAsStringAsync();

Here is my list of permissions for the token requesting app in azure

Permissions

What am I missing here ? Any help will be apreciated.


Solution

  • The error usually occurs if your service principal does not have required roles or permissions to perform the operation.

    I registered one Azure AD application and added same API permissions as below:

    enter image description here

    Now, I generated access token using client credentials flow via Postman with below parameters:

    POST https://login.microsoftonline.com/tenantId/oauth2/v2.0/token
    grant_type:client_credentials
    client_id: appId
    client_secret: secret 
    scope: https://management.azure.com/.default
    

    Response:

    enter image description here

    When I tried to purge the Azure CDN cache by calling below API, I too got same error like this:

    POST https://management.azure.com/subscriptions/subid/resourceGroups/RG/providers/Microsoft.Cdn/profiles/profile1/endpoints/endpoint1/purge?api-version=2023-05-01
    Authorization: Bearer <token>
    
    {
      "contentPaths": [
        "/folder1"
      ]
    }
    

    Response:

    enter image description here

    To resolve the error, make sure to assign CDN Endpoint Contributor role to the service principal at required scope as it has this permission in it Microsoft.Cdn/profiles/endpoints/purge/action .

    In my case, I assigned CDN Endpoint Contributor role to the service principal under resource group scope like below:

    enter image description here

    After assigning the role, I ran below API call by generating access token again and got response successfully like this:

    POST https://management.azure.com/subscriptions/subid/resourceGroups/RG/providers/Microsoft.Cdn/profiles/profile1/endpoints/endpoint1/purge?api-version=2023-05-01
    Authorization: Bearer <token>
    
    {
      "contentPaths": [
        "/folder1"
      ]
    }
    

    Response:

    enter image description here

    In your case, make sure to assign CDN Endpoint Contributor role to the service principal under required scope.

    Reference: Azure built-in roles - Azure RBAC | Microsoft