使用 OAuthCard 调用 Azure Function

Using OAuthCard to call Azure Function

我有一个 V3 机器人,我想从一个对话框中调用一个被 Azure AD V1 锁定的 Azure 函数。我想从 Azure AD 获取令牌并使用此令牌访问 Azure Functions。

我正在尝试将 OAuthCard 与 Azure AD 提供商一起使用,并将资源 URL 设置为我的 Azure 函数 https://my-function-app.azurewebsites.net

当我登录 OAuthCard 时出现错误 "The application named https://my-function-app.azurewebsites.net was not found in the tenant named 880fb54d-f717-4364-9a22-df9ac5c77f6d"

Function App 确实住在那个租户里。以下是在机器人频道注册中配置的 OAuth 连接设置。

是否可以使用 OAuthCard 调用被 Azure AD 锁定的 Azure Function?

I have a V3 Bot, and from a Dialog I want to call an Azure Function which is locked down by Azure AD V1. I want to get a token from Azure AD and use this token to access the Azure Function.

如果可能,您可以直接请求从您的机器人应用程序获取 https://my-function-app.azurewebsites.net 的访问令牌,如下所示:

//Acquire token

var client = new RestClient($"https://login.microsoftonline.com/{tenantId}/oauth2/token");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", $"grant_type=client_credentials&client_id={client_id}&client_secret={client_secret}&resource={resource}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

var tokenResponse = JsonConvert.DeserializeObject<TokenResponse>(response.Content);

var access_token = tokenResponse.access_token;

令牌响应class:

public class TokenResponse
{
    public string token_type { get; set; }
    public string expires_in { get; set; }
    public string ext_expires_in { get; set; }
    public string expires_on { get; set; }
    public string not_before { get; set; }
    public string resource { get; set; }
    public string access_token { get; set; }
}

然后您可以 call/access 使用该访问令牌的函数应用端点。

//Call Azure function using access token

var client2 = new RestClient($"https://xxxxfunction.azurewebsites.net/api/HttpTriggerFunc?code=CR9X9VsIattzWybmvasvpjAXfQU2feRuV3jXC6p/0B2AlFgl4LwPMw==");
var request2 = new RestRequest(Method.POST);
request2.AddHeader("Authorization", $"Bearer {access_token}");
request2.AddHeader("Content-Type", "application/json");

request2.RequestFormat = DataFormat.Json;
request2.AddBody(new { name = "Fei Han" });

IRestResponse response2 = client2.Execute(request2);

var funcResponse = JsonConvert.DeserializeObject<string>(response2.Content);

await context.PostAsync($"Response returned from Azure function: {funcResponse}.");

测试结果:

注:

详细信息请查看"Service to service calls using client credentials"