gpt4 book ai didi

c# - 尝试激活图形 API 时无法解析类型 'Microsoft.Identity.Web.ITokenAcquisition' 的服务

转载 作者:行者123 更新时间:2023-12-05 08:39:24 25 4
gpt4 key购买 nike

.net core 2.2项目。我正在为我的 api 实现基于组的授权。我关注了https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/tree/886f2ad2bf6add922c7998fb592e3d4088f9cf4e/5-WebApp-AuthZ/5-2-Groups来实现这一点。首先我添加了https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/tree/886f2ad2bf6add922c7998fb592e3d4088f9cf4e/Microsoft.Identity.Web到我的项目。然后我开始在我的startup.cs中添加策略,如下所示。

services.AddAuthorization(options =>
{
options.AddPolicy("GroupsCheck", policy =>
policy.Requirements.Add(new GroupsCheckRequirement("2a39995a-8fd1-410e-99e2-11cf6046090d")));
});

services.AddScoped<IAuthorizationHandler, GroupsCheckHandler>();

然后我添加了GroupsCheckHandler.cs

public class GroupsCheckHandler : AuthorizationHandler<GroupsCheckRequirement>
{
private readonly ITokenAcquisition tokenAcquisition;
private readonly IMSGraphService graphService;

public GroupsCheckHandler(ITokenAcquisition tokenAcquisition, IMSGraphService MSGraphService)
{
this.tokenAcquisition = tokenAcquisition;
this.graphService = MSGraphService;
}
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context,
GroupsCheckRequirement requirement)
{
string accessToken = await tokenAcquisition.GetAccessTokenOnBehalfOfUserAsync(new[] { Constants.ScopeUserRead, Constants.ScopeDirectoryReadAll });

User me = await graphService.GetMeAsync(accessToken);

IList<Group> groups = await graphService.GetMyMemberOfGroupsAsync(accessToken);

var result = false;
foreach (var group in groups)
{
if (requirement.groups.Equals(group.Id))
{
result = true;
}
}

if (result)
{
context.Succeed(requirement);
}

}
}

然后我在 api 中添加了授权属性,如下所示。

[Authorize(Policy = "GroupsCheck")]
[Route("api/[controller]")]
[ApiController]

现在,每当我尝试访问任何 api 时,都会遇到异常。

System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Identity.Web.ITokenAcquisition' while attempting to activate 'LocationServicesAPI.Services.GroupsRequirements.GroupsCheckHandler'.

有人可以帮我找出这个问题的根本原因吗,或者如果我做错了或者缺少任何配置,有人可以在这方面帮助我。任何帮助将不胜感激。谢谢

最佳答案

依赖项注入(inject)尝试实例化 ITokenAcquisition 实例但失败。这可能是由于 Startup.cs 中的配置存在问题。您需要确保在配置身份验证时调用 EnableTokenAcquisitionToCallDownstreamApiAddInMemoryTokenCaches

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(Configuration, "AzureAd")
.EnableTokenAcquisitionToCallDownstreamApi()
.AddInMemoryTokenCaches();

关于c# - 尝试激活图形 API 时无法解析类型 'Microsoft.Identity.Web.ITokenAcquisition' 的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59700833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com