//Cloud notes from my desk -Maheshk

"Fortunate are those who take the first steps.” ― Paulo Coelho

[AAD] How to create Service Principal through CLI

There are multiple ways to generate the Service Principal for Azure AD. Say, through portal, CLI or PowerShell. I always used Azure portal for this registration. But started liking CLI way of generating principal which is very simple and easy to register and generate the required keys and move on. Yes, many times you would find this step as a prerequisites or in mid way to continue say Azure Data Lake Analytics query or ADAL programming.

$ az login
$ az account list -o table

$ az ad sp create-for-rbac --name MikkyDemoTraining --years 1

output:
{
"appId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"displayName": "MikkyDemoTraining",
"name": "http://MikkyDemoTraining",
"password": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"tenant": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
}


Ps: Take note of the password value for later references, otherwise you may need to regenerate again.

For more detail – https://docs.microsoft.com/en-us/cli/azure/create-an-azure-service-principal-azure-cli?view=azure-cli-latest

Advertisements

2018-01-31 Posted by | AAD | | Leave a comment

[Azure CDN] How to Purge CDN content from C# code

Recently I had a chance to work on this ask where one of the developer wanted a sample code to purge the CDN content by hitting this REST API instead portal. Initially I followed this link but do not wanted to give my username and password as explained there for AAD authentication. I wanted to get my app registered with AAD as WebApp and then work with ClientID and Client Secret way to the get the bearer token for making the REST API call. It worked rightly after so many attempts, so would like to leave the steps here for easy reference.

Step1: Register your Web Application in AAD (portal.Azure.com) and get the Client ID and Secret generated.

8

Step2) Select the required permissions as below.

7

6

Step3) Add this application as a contributor to the CDN Endpoint which we wanted to purge.

CDN Profile > CDN Endpoint > Access Control (IAM) > Add our Web Application which is going to hit this endpoint to purge

10

9

Step4) Now run our sample code to get invoke purged call

image       

Step5) On success.

5

Sample C# code used for purge ( from WebApplication )

       public ActionResult Contact()
        {
            GetAccessTokenAndMakePurgeCall();

            ViewBag.Result = “Done – Purged all.. “;

            return View();
        }

        private static void GetAccessTokenAndMakePurgeCall()
        {
            string clientId = “e32a947c-136e-xxxxxx-15eed998b592”;
            string clientSecret = “Ga9y3/9wNklz3Ft/xxxxxxxxgqpNM5KZxxxXM=”;
            string uri = @”
https://management.azure.com/subscriptions/xxxxxx-xxxxx/resourcegroups/emptybincdnrg/providers/Microsoft.Cdn/profiles/bluehousecdn/endpoints/bhep/purge?api-version=2015-06-01″;

            var authenticationContext = new AuthenticationContext(“https://login.microsoftonline.com/microsoft.onmicrosoft.com”);
            ClientCredential clientCredential = new ClientCredential(clientId, clientSecret);
            Task<AuthenticationResult> resultstr = authenticationContext.AcquireTokenAsync(“
https://management.core.windows.net/”, clientCredential);

            WebClient client = new WebClient();
            //authentication using the Azure AD application
            var token = resultstr.Result.AccessToken;
            client.Headers.Add(HttpRequestHeader.Authorization, “Bearer ” + token);
            client.Headers.Add(“api-version:2015-06-01”);
            client.Headers.Add(“Content-Type”, “application/json”);

            var bodyText = string.Empty;

            //For individual files
            //dynamic content = new { ContentPaths = new List<string>() { “/1.jpg”, “/2.jpg” } };

            //bodyText = JsonConvert.SerializeObject(content);

            //For purge all (*.*)
            //bodyText = “{“ContentPaths”:[“/*”]}”;

            try
            {
                var result = client.UploadString(uri, bodyText);
            }
            catch (Exception ew)
            {
                //handle the exception here
            }
        }

 

On running fiddler, we can see the header details are formed correctly and getting the bearer token to proceed.

image

On success, you could see “202” in the response which means our purge request has been accepted.

image

 

<update:4/18>

How to purge the CDN content using Postman ( assuming you have the valid bearer token )

1

2

On success, you would see “202” – accepted.

</update>

Hope this helps.

 

<Disclaimer> 

              a) This sample code provided here is for the purpose of illustration only and is not intended to be used in a production environment as it is.

              b) ContentPaths should be carefully checked. The path “/*” should be used only when you want to purge all the contents otherwise specify the resource path.

</Disclaimer> 

2017-04-01 Posted by | .NET, AAD, Azure, CDN | | 3 Comments

Add-AzureAccount issue: Your Azure credentials have not been set up or have expired

For some reason, I started experiencing this issue. Tried clearing the local cache, temp folders or cookies etc but none helped. So grabbed fiddler log to see what is going wrong. Noticed it was having the very old session token (3-4 months older) getting served for some reason and no clue where it lies also. Checked few command lets to clear this out within PS and noted Clear-AzureProfile flushed the older tokens which resolved this issue.

PS C:WINDOWSsystem32> Add-AzureAccount

Id Type Subscriptions Tenants

— —- ————- ——-

xxxx@microsoft.com User xx-c5bc-xx-a7e0-xx{xxx-86f1-41af-91ab-xxxx}

PS C:WINDOWSsystem32> Get-AzureRoleSize

Get-AzureRoleSize : Your Azure credentials have not been set up or have expired, please run Add-AzureAccount to set up your Azure credentials.

At line:1 char:1

+ Get-AzureRoleSize

+ ~~~~~~~~~~~~~~~~~

+ CategoryInfo : CloseError: (:) [Get-AzureRoleSize], ArgumentException

+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.ServiceManagement.HostedServices.AzureRoleSizeCommand

 

Solution:-

Run the Clear-AzureProfle Commandlet and then try Add-AzureAccount to get the valid bearer token to continue.

PS C:WINDOWSsystem32> Clear-AzureProfile –Force

Let me know if you see this issue and root cause for this.

Happy scripting…

2017-01-19 Posted by | AAD, Azure, Powershell | | 9 Comments

How to list all available VM sizes in a region using .NET (ARM endpoint)

Today, I had a query from a developer asking how to silent authenticate and fetch the list of available VM’s sizes from a particular region using .NET code. They wanted to fetch this detail from their worker role more precisely. They wanted to call the URI as in this article silent authenticated https://msdn.microsoft.com/en-us/library/azure/mt269440.aspx

Method Request URI
GET https://management.azure.com/subscriptions/{subscription-id}/providers/Microsoft.Compute/locations/{location}/vmSizes?api-version={api-version}

On first sight, I thought this as an RDFE endpoint(older portal/SMAPI), but on closer look this turned to be an ARM end point.

How to identify the url is an RDFE/ARM endpoint?

Please note, for RDFE end point we may have to either use certificate based or native client way of authentication.

Since this is an ARM endpoint, we need to follow the service principal way to get the bearer token which is needed for the URI GET call’s.

Step1:-

Perform the following action one by one carefully as in this URL –  https://azure.microsoft.com/en-us/documentation/articles/resource-group-create-service-principal-portal/

  1. Create an Active Directory application
  2. Get client id and authentication key
  3. Get tenant id
  4. Set delegated permissions
  5. Assign application to role

Step2:-

using System;
using System.IO;
using System.Net;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{

            var context = new AuthenticationContext(“https://login.microsoftonline.com/+ “your_tenantid”);
ClientCredential credential = new ClientCredential(“your_client_ID”, “your_client_secret”);
AuthenticationResult result = context.AcquireToken(“
https://management.azure.com/”, credential);
var token = result.CreateAuthorizationHeader().Substring(“Bearer “.Length);

            string uri = @”https://management.azure.com/subscriptions/<your_subscription_Id>/providers/Microsoft.Compute/locations/Southeast Asia/vmSizes?api-version=2015-05-01-preview”;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Headers.Add(“Authorization:Bearer ” + token);
var response = request.GetResponse().GetResponseStream();
var output = new StreamReader(response).ReadToEnd();

            Console.WriteLine(output);
}
}
}

P.s:- I have used Adal 2.28.2.795 to avoid async complexities.

on executing,

image

2016-10-19 Posted by | .NET, AAD, ARM, Azure, Azure Dev, C#, PaaS | | 1 Comment

   

%d bloggers like this: