C# console application authentication session
Asked Answered
E

1

6

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).

Endear answered 7/5, 2019 at 4:47 Comment(1)
Is az meant to be azure? If so use the latter and flag the former as a synonymMantelet
L
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.

Labret answered 7/5, 2019 at 9:54 Comment(2)
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?Endear
If you want to get the access token directly after enter user credential, you could use implicit grant flow.Labret

© 2022 - 2024 — McMap. All rights reserved.