我正在尝试连接到 Azure AD 和 Microsoft Graph 以获取用户照片。我正在使用 .NET 6 Razor Pages,这是我在 Program.cs 中的配置
string[] initialScopes = builder.Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ');
builder.Services
.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
.AddMicrosoftGraph(builder.Configuration.GetSection("DownstreamApi"))
.AddInMemoryTokenCaches();
当我在此处放置断点时,我可以看到它具有我在 appsettings.json 设置的
initialScopes
值
在我的index.cshtml.cs中,这是我的代码:
[Authorize]
public class IndexModel : PageModel
{
private readonly GraphServiceClient _graphServiceClient;
private readonly MicrosoftIdentityConsentAndConditionalAccessHandler _consentHandler;
private string[] _graphScopes;
public IndexModel(GraphServiceClient graphServiceClient,
MicrosoftIdentityConsentAndConditionalAccessHandler consentHandler, IConfiguration configuration)
{
_graphServiceClient = graphServiceClient;
_consentHandler = consentHandler;
// Capture the Scopes for Graph that were used in the original request for an Access token (AT) for MS Graph as
// they'd be needed again when requesting a fresh AT for Graph during claims challenge processing
_graphScopes = configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ');
}
[AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")]
public async Task OnGetAsync()
{
}
}
但是在
app.Run();
处失败了。错误信息是:
“无法解析类型的服务 'Microsoft.Identity.Web.MicrosoftIdentityConsentAndConditionalAccessHandler' 尝试激活时
我对此进行了谷歌搜索,它说我需要
EnableTokenAcquisitionToCallDownstreamApi
,但我想我已经配置了这个。
我遇到了同样的问题,最终起作用的是添加以下代码。
services.AddServerSideBlazor()
.AddMicrosoftIdentityConsentHandler();
此外,您还需要在 AddMicrosoftIdentityWebApp 中进行以下配置设置来应对 CAE 挑战。
“客户端能力”:[“cp1”]