[英]WPF app Accessing Azure Function with AAD
我已经在Azure Functions中创建了一个示例函数。 我已经使用AAD对其进行了保护。 我可以成功转到URL,使用我的Office 365帐户登录,然后该函数运行。
我在AAD中为WPF客户创建了另一个应用程序。 我可以使用我的Office 365凭据成功登录到WPF客户端。 然后,我在AAD中为此应用创建了一个permision,以访问Azure Function AAD应用。
这是我的问题:如何使用WPF应用程序中的登录令牌访问Azure功能?
我遍历了大约十二个不同的教程,展示了如何进行设置,每个教程都无法真正验证对函数的调用。
我想念什么?
经过大量研究和反复试验,终于可以使用我的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();
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.