c# - 调用受 Azure Active Directory 保护的 WebService
问题描述
我已将 Web 应用程序部署到 Azure 应用服务并设置应用服务身份验证以使用 Active Directory。
在控制台应用程序中,我有以下代码。
string baseUrl = "https://testapp.azurewebsites.net/Admin/GetCustomers";
string sAuthority = "https://login.microsoftonline.com/{tennant ID}“;
string sClient = “{“Client ID};
string sClientSecret = “{“ClientSecret};
IConfidentialClientApplication app;
app = ConfidentialClientApplicationBuilder.Create(sClient)
.WithClientSecret(sClientSecret)
.WithAuthority(new Uri(sAuthority))
.Build();
string[] scopes = new string[] { "https://testapp.azurewebsites.net/Admin/.default" };
AuthenticationResult result = null;
result = app.AcquireTokenForClient(scopes).ExecuteAsync().Result;
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = httpClient.GetAsync(baseUrl).Result;
if (response.IsSuccessStatusCode)
{
string json = response.Content.ReadAsStringAsync().Result;
JObject resultData = JsonConvert.DeserializeObject(json) as JObject;
Console.WriteLine("Finished Loading Data!");
}
else
{
Console.WriteLine("Error Happened");
}
根据您的指南,我在 ActiveDirectory 中注册了 2 个应用程序
- 服务器应用程序具有公开的 API https://testapp.azurewebsites.net/Admin/范围为 GetCustomers
- Web URI - https://testapp.azurewebsites.net/auth-response和https://testapp.azurewebsites.net
客户端应用程序对此范围具有权限作为管理员我授予它并创建了一个 ClinetSecret
我忘了做什么?史蒂夫
解决方案
这不起作用,因为您正在获取图形 api 范围的令牌:
string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
result = app.AcquireTokenForClient(scopes).ExecuteAsync().Result;
如果您改为调用图形 api,则从该调用返回的令牌将起作用:
string baseUrl = "https://graph.microsoft.com/v1/me"
但这不是你所追求的。您需要做的是创建一个范围,该范围提供对您的 API 的访问,以便 AAD 可以发出适当的令牌。
为此,您需要在管理托管 API 的 Web 应用程序时在 Azure 门户中“公开 API”。您可以使用您创建的自定义命名范围,或者[app id uri]/.default
改为使用。
推荐阅读
- scikit-learn - 无法使用 sklearn 0.24.1 导入 LSHForest
- javascript - 如何在 PHP 中使用路径而不是 GET 变量?
- graphql - 如何在 nuxt 应用程序中获取特定的 GraphQL 对象?
- javascript - React child (found: object with keys {}) 不会渲染文件
- docker - 如何使用 openjdk11 和 dockerfile 在容器中安装 java 11
- dht - Kadelmia 路由表 - 是否需要双向路由?
- python - mp3 音频文件的 Pydub AudioSegment.from_file() 失败:解码失败。ffmpeg 返回错误代码:1,
- r - 从矩阵、参数列表中为 R 的优化函数创建向量和解析参数的技术——重构参数的巧妙方法?
- haskell - 解析索引缓存失败(Data.Binary.Get.runGet 在位置 16:)
- r - 使用 pmap 遍历 tibble 的行