我能够成功完成以下工作。
我的问题是,我如何能够以编程方式完成同样的工作,比如说,从我创建的控制台应用程序中? 我是否会收到输入我的微软凭证的提示,或者我是否可以以某种方式将凭证配置为传递给控制台应用程序进行验证?
在这里,我提供了一个例子,供您参考。该代码首先获得访问令牌,然后使用访问令牌在控制台应用程序中请求你的函数URL。在获取访问令牌时,我在代码中提供了两种方式(密码授予和客户端认证授予),你可以选择其中任何一种。
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; }
}
}
以上一些参数的来源,请先到你在AD中注册的应用中去找。
你可以找到 client_id
和 tenantId
在下面的截图中。