0
votes

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?

1
Do you want to complete the above operations in the form of programming?Carl Zhao
Hi sergeidave, may I know which flow do you want to use when you do the authentication before request the function url ? Just use credentials or you can also accept password flow, client credential flow... ?Hury Shen
@CarlZhao So, my secured azure function will be called by another application when deployed to production, but I was also trying to do some integration testing where I could hit the secured azure functions from my integration tests. My assumption is that there should be a way to authenticate, and then request the authorization token completely through code.sergeidave
@HuryShen I guess that's the part I don't have so clear, as I'm fairly new to Oauth2 as well as Active Directory. When I run the above steps through Postman, I get a window prompt that asks me to login with my Microsoft credentials, after which Postman is then able to obtain the access token to finally be able to hit the function endpoint. But this window popup thing, how can that be sort of avoided and still complete authentication purely through code, without any popups? Is that possible?sergeidave
Hi @sergeidave May I know if the solution I provided works ?Hury Shen

1 Answers

0
votes

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