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:
You need to new a client secret in the screenshot below, it is the client_secret
parameter in the code above.
The scope
parameter in my code comes from here: