我已经在Azure Functions中创建了一个示例函数。我已经使用AAD对其进行了保护。我可以成功转到URL,使用我的Office 365帐户登录,该功能将运行。
我在AAD中为WPF客户端创建了另一个应用程序。我可以使用我的Office 365凭据成功登录到WPF客户端。然后,我在AAD中为此应用创建了一个权限以访问Azure Function AAD应用。
这是我的问题: 如何使用WPF应用程序中的登录令牌访问Azure功能?
我遍历了大约十二个不同的教程,展示了如何进行设置,但每个教程都未能真正验证对函数的调用。
我想念什么?
答案 0 :(得分:0)
经过大量研究和反复试验,终于可以使用我的Office365帐户登录并访问Azure功能。
Azure Active Directory还允许您注册本机客户端,从而可以更好地控制权限映射。如果希望使用诸如Active Directory身份验证库之类的库来执行登录,则需要使用此方法。
https:// {AD TENANT} .onmicrosoft.com / {SERVICE APP ID} / user_impersonation
从您的客户端应用程序。安装nuget Microsoft.Identity.Client
using Microsoft.Identity.Client;
using Newtonsoft.Json.Linq;
using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace TestAzureFunctionLogin
{
public class ManualTestApp
{
static string ClientId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; //replace with AppID from Client App Azure AD registration
static string ServiceId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; //replace with AppID from Service App Azure AD registration
static string Scope = $"{ServiceId}/user_impersonation";
static string Authority = "https://login.microsoftonline.com/organizations";
string[] _scopes => new string[] { Scope };
private PublicClientApplication _clientApp = new PublicClientApplication(ClientId, Authority);
private AuthenticationResult authResult;
public PublicClientApplication ClientApp => _clientApp;
public async Task LoginAsync()
{
var user = (await ClientApp.GetAccountsAsync()).FirstOrDefault();
authResult = await ClientApp.AcquireTokenAsync(_scopes, user);
}
public async Task<string> CallAzureFunction(string url)
{
return await GetHttpContentWithToken(url, authResult.AccessToken);
}
//Code taken from somewhere on the Microsoft Website
public async Task<string> GetHttpContentWithToken(string url, string token)
{
var httpClient = new System.Net.Http.HttpClient();
System.Net.Http.HttpResponseMessage response;
try
{
var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);
//Add the token in Authorization header
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
response = await httpClient.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
return content;
}
catch (Exception ex)
{
return ex.ToString();
}
}
}
}