sergeidave
sergeidave

Reputation: 692

How do I Authenticate against Active Directory to hit a secured Azure Function from Console App?

I was able to successfully accomplish the following:

  1. Enabled Authentication/Authorization for my Azure Function.
  2. Created an App Registration in Azure for my function to be called securely through AAD auth.
  3. I can successfully authenticate, get a token and hit my Azure Function from Postman.

My question is how can I programmatically do the same, say, from a console application I created? Will I get a prompt to enter my Microsoft credentials or can I some how configure the credentials to be passed to the console app for authentication?

Upvotes: 0

Views: 307

Answers (1)

Hury Shen
Hury Shen

Reputation: 15754

Here I provide a sample for your reference. The code get access token first and then use the access token to request your function url in console app. When get the access token, I provide two ways(password grant and client_credential grant) in code, you can choose any one of them.

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;

namespace ConsoleApp16
{
    class Program
    {
        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            //Get a access token(password grant)
            HttpClient client = new HttpClient();
            var values = new Dictionary<string, string>
            {
                { "client_id", "<your app client id>" },
                { "scope", "<scope>" },
                { "username", "<username>" },
                { "password", "<password>" },
                { "grant_type", "password" },
                { "client_secret", "<your app client secret>" }
            };

            var content = new FormUrlEncodedContent(values);
            var response = await client.PostAsync("https://login.microsoftonline.com/<your tenant id>/oauth2/v2.0/token", content);
            String responseString = await response.Content.ReadAsStringAsync();
            dynamic json = JsonConvert.DeserializeObject<Response>(responseString);
            String accessToken = json.access_token;

            //You can also get the access token by the code below(client_credential grant)
            /*
            HttpClient client = new HttpClient();
            var values = new Dictionary<string, string>
            {
                { "client_id", "<your app client id>" },
                { "scope", "<scope>" },
                { "client_secret", "<your app client secret>" },
                { "grant_type", "client_credentials" },
            };

            var content = new FormUrlEncodedContent(values);
            var response = await client.PostAsync("https://login.microsoftonline.com/<your tenant id>/oauth2/v2.0/token", content);
            var responseString = await response.Content.ReadAsStringAsync();
            dynamic json = JsonConvert.DeserializeObject<Response>(responseString);
            String accessToken = json.access_token;
            */

            //Use the access token to request your function url
            HttpClient client1 = new HttpClient();
            client1.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
            var response1 = await client1.GetAsync("https://myfunapp.azurewebsites.net/api/myHTTPtrigger?name=azure");
            String responseString1 = await response1.Content.ReadAsStringAsync();
            Console.WriteLine(responseString1);
        }
    }

    public class Response
    {
        public string access_token { get; set; }

    }
}

For the source of some parameters above, please go to your the app which registered in AD first.

You can find the client_id and tenantId in the screenshot below: enter image description here

You need to new a client secret in the screenshot below, it is the client_secret parameter in the code above. enter image description here

The scope parameter in my code comes from here: enter image description here

Upvotes: 0

Related Questions