【发布时间】:2021-10-12 16:34:41
【问题描述】:
我试图在 ASP.NET Core 5 MVC 中了解“现代”身份验证方法,并处理用于调用外部服务的 OAuth 和访问令牌。
我在 Azure 中有一个应用注册,设置正常 - 这些是该应用的 API 权限:
我的目标是调用 MS Graph(多次调用)和 MS Dynamics365,以收集一些信息。我已经设法在我的 MVC 应用程序中使用 OAuth(或者它是 OpenID Connect?我不太确定如何区分这两者)设置身份验证,就像这样(在 Startup.cs 中):
/* in appsettings.json:
"MicrosoftGraph": {
"Scopes": "user.read organization.read.all servicehealth.read.all servicemessage.read.all",
"BaseUrl": "https://graph.microsoft.com/v1.0"
},
*/
public void ConfigureServices(IServiceCollection services)
{
List<string> initialScopes = Configuration.GetValue<string>("MicrosoftGraph:Scopes")?.Split(' ').ToList();
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
.AddInMemoryTokenCaches();
// further service setups
}
它工作正常 - 系统提示我登录,提供我的凭据,并且在我的 MVC 应用程序中,我可以在登录后检查声明主体及其声明 - 到目前为止,一切似乎都很好。
下一步是调用下游 API。我研究了一些博客文章和教程,并根据给定调用所需的scope 的名称提出了这个获取访问令牌的解决方案。这是我的代码(在 Razor 页面中,用于显示从 MS Graph 获取的数据):
public async Task OnGetAsync()
{
List<string> scopes = new List<string>();
scopes.Add("Organization.Read.All");
// fetch the OAuth access token for calling the MS Graph API
var accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(scopes);
HttpClient client = _factory.CreateClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
client.DefaultRequestHeaders.Add("Accept", "application/json");
string graphUrl = "https://graph.microsoft.com/v1.0/subscribedSkus";
string responseJson = await client.GetStringAsync(graphUrl);
// further processing and display of data fetched from MS Graph
}
对于 MS Graph 范围,这工作得很好 - 我得到了我的访问令牌,我可以将它传递给我的 HttpClient 并且对 MS Graph 的调用成功并且我得到了所需的信息。
当尝试使用相同的方法获取访问令牌以调用 MS Dynamics 时,挑战开始。我假设我只是指定了在 Azure AD 注册中定义的 API 权限的名称 - user_impersonation - 像这样:
public async Task OnGetAsync()
{
List<string> scopes = new List<string>();
scopes.Add("user_impersonation");
var accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(scopes);
// further code
}
但现在我得到的只是错误 - 就像这个:
处理请求时发生未处理的异常。
MsalUiRequiredException:AADSTS65001:用户或管理员未同意使用 ID 为“257a582c-4461-40a4-95c3-2f257d2f8693”、名为“BFH_Dyn365_Monitoring”的应用程序。为此用户和资源发送交互式授权请求。
这很有趣,因为管理员同意已被授予 - 所以我不太确定问题是什么.....
然后我想也许我需要将 user_impersonation 添加到初始范围列表中(在 appsettings.json 中定义并在 Startup.ConfigureServices 方法中使用) - 但添加这会导致另一个有趣的错误:
处理请求时发生未处理的异常。
OpenIdConnectProtocolException:消息包含错误:'invalid_client',error_description:'AADSTS650053:应用程序'BFH_Dyn365_Monitoring'要求资源'00000003-0000-0000-c000-000000000000'上不存在的范围'user_impersonation'。联系应用供应商。
奇怪的是 - 正如您在此处的第一个屏幕截图中看到的那样 - 应用注册中存在 IS 范围 - 所以我不完全确定为什么会引发此异常....
任何人都可以从使用 OAuth 令牌调用 MS Dynamics 的经验中了解一下吗?这是根本不可能的,还是我在某处遗漏了一两步?
谢谢!马克
【问题讨论】:
标签: c# oauth microsoft-graph-api access-token dynamics-365