问题描述
我正在尝试创建一个 .NET 控制台应用程序来验证 Azure 函数应用的用户身份。我想使用他们的 AD 凭据对用户进行身份验证,然后基于它创建一个令牌。我相信我需要启用“公共客户端流”才能实现这一点。我对此很陌生,但在多次尝试失败后,我在“公开 API”部分设置了应用程序 ID URI 和范围后设法让它工作。我相信清单将此属性称为“identifierUris”。根据一些调查结果,公共访问和 identifierUris 不能同时使用。 有没有其他方法可以实现这一目标?任何关于为什么这不理想的解释或推理也将不胜感激。
这是我们用来检索令牌并使用它的代码:
var publicclient = PublicclientApplicationBuilder
.Create(clientId)
.WithAuthority(authorityUri)
.WithRedirectUri(redirectUri)
.Build();
var accesstokenRequest = publicclient.AcquiretokenInteractive(scopes);
var accesstoken = await accesstokenRequest.ExecuteAsync();
restRequest.AddHeader("authorization","Bearer " + token);
这是创建 Azure AD 应用程序的 Pulumi 代码,其中 functionApp
是我们尝试授权的 Pulumi.Azure.AppService.FunctionApp
:
var azureApp = new AzureAD.Application(name,new AzureAD.ApplicationArgs
{
displayName = name,AvailabletoOtherTenants = false,Homepage = "https://VisualStudio/SPN",Oauth2AllowImplicitFlow = true,ReplyUrls = { "http://localhost" },IdentifierUris =
{
functionApp.DefaultHostname.Apply(dnsName => "https://" + dnsName)
},Publicclient = true
},new CustomresourceOptions {DependsOn = functionApp});
当 Publicclient
设置为 false 时,部署正常。当它设置为 true
时,底层 API 调用会返回 400 错误并带有以下文本:
Property identifierUris is invalid
因此,我们将 Publicclient
设置为 false,然后在门户中手动将其更新为 true,效果很好:
我们缺少什么?
解决方法
您不需要将 PublicClient
设置为 true
,因为它适用于 ROPC 流、设备代码流或 Windows 集成身份验证流,如屏幕截图所示。
但根据您的代码,我认为您没有使用任何三个身份验证流程。
您应该创建一个代表 API/服务器端(您的 Azure 函数应用)的新应用注册并执行“公开 API”。
在代表客户端(.NET 控制台应用程序)的应用注册中添加范围/权限(由 API/服务器端公开)。
使用PublicClientApplicationBuilder
,只需要修改客户端app注册的manifest文件中的"allowPublicClient": true
即可。不要在“公开 API”部分添加任何 IdentifierUris
或设置应用程序 ID URI 和范围,因为这应该在代表 API/服务器端的应用注册中完成。