5

How could someone implement the az login (Azure CLI) experience in a C# Console application?

In that case, a browser window is opened, the user authenticates and after that he can access the private resources. My guess is that the authentication token is stored somewhere, but where? Session variable, file..?

Update

I found out that there is a folder ~/.azure storing the relevant information. So the question is more on the first part (starting a browser and getting the resulting token).

fra
  • 3,488
  • 5
  • 38
  • 61
  • Is `az` meant to be `azure`? If so use the latter and flag the former as a synonym –  May 07 '19 at 05:09

1 Answers1

0

How could someone implement the az login (Azure CLI) experience in a C# Console application?

1.Starting a browser with Process.Start(@"http://url");. After user enter his credential, you will get the authorization code. Copy it.

2.Get an authorization code.

3.Get access token with following code:

using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Add("ContentType", "application/json");
    var requestURl = new Uri($"https://login.microsoftonline.com/xxxxxxxxxxxxxxxxxxxx/oauth2/v2.0/token");
    string body = "{\"client_id\": \"3c35ed0b-a441-4c57-9d1c-3a3b0392d9c3\",\"code\":\"the_code_you_copy_in_the_second_step\",\"redirect_uri\": \"https://localhost\",\"grant_type\": \"authorization_code\",\"client_secret\": \"xxxxxxxxxxxxxx\",\"scope\": \"user.read\"}";
    var stringContent = new StringContent(body, Encoding.UTF8, "application/json");
    var response = client.PostAsync(requestURl, stringContent).Result;
}

4.The result:enter image description here

For more detials about how to get authorization code and access token you could refer to this article.

Joey Cai
  • 18,968
  • 1
  • 20
  • 30
  • Thank you @Joey, but I'm expecting that the entire operation is automated in the CLI. How can I get the value from step 1? – fra May 07 '19 at 13:35
  • If you want to get the access token directly after enter user credential, you could use [implicit grant flow](https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-implicit-grant-flow). – Joey Cai May 08 '19 at 02:32