gpt4 book ai didi

azure - ASP.NET Core token 获取异常

转载 作者:行者123 更新时间:2023-12-02 06:40:11 29 4
gpt4 key购买 nike

在关注this guide时要设置新的 AzureAD 应用程序,我在完成第 3 页后遇到此错误:

System.AggregateException
HResult=0x80131500
Message=Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.Identity.Web.ITokenAcquisition Lifetime: Scoped ImplementationType: Microsoft.Identity.Web.TokenAcquisition': Unable to resolve service for type 'Microsoft.Identity.Web.TokenCacheProviders.IMsalTokenCacheProvider' while attempting to activate 'Microsoft.Identity.Web.TokenAcquisition'.)
Source=Microsoft.Extensions.DependencyInjection
StackTrace:
at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(IEnumerable`1 serviceDescriptors, ServiceProviderOptions options)
at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options)
at Microsoft.Extensions.DependencyInjection.DefaultServiceProviderFactory.CreateServiceProvider(IServiceCollection containerBuilder)
at Microsoft.Extensions.Hosting.Internal.ServiceFactoryAdapter`1.CreateServiceProvider(Object containerBuilder)
at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
at Microsoft.Extensions.Hosting.HostBuilder.Build()
at Jobbi3.Program.Main(String[] args) in C:\Users\jakes\Desktop\Jobbi3\Jobbi3\Program.cs:line 16

This exception was originally thrown at this call stack:
[External Code]

Inner Exception 1:
InvalidOperationException: Error while validating the service descriptor 'ServiceType: Microsoft.Identity.Web.ITokenAcquisition Lifetime: Scoped ImplementationType: Microsoft.Identity.Web.TokenAcquisition': Unable to resolve service for type 'Microsoft.Identity.Web.TokenCacheProviders.IMsalTokenCacheProvider' while attempting to activate 'Microsoft.Identity.Web.TokenAcquisition'.

Inner Exception 2:
InvalidOperationException: Unable to resolve service for type 'Microsoft.Identity.Web.TokenCacheProviders.IMsalTokenCacheProvider' while attempting to activate 'Microsoft.Identity.Web.TokenAcquisition'.

我不确定是什么原因导致了这个问题,我希望找到其他可能遇到过这个问题的人。另外,指南中展示了如何设置 Multi-Tenancy 应用程序,但我对此特定应用程序使用单个租户。

这是我的启动文件:

using Jobbi3.Util;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.Graph;
using System.Net;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Threading.Tasks;

namespace Jobbi3
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(options => {
Configuration.Bind("AzureAd", options);
options.Prompt = "select_account";
options.Events.OnTokenValidated = async context =>
{
var tokenAcquisition = context.HttpContext.RequestServices
.GetRequiredService<ITokenAcquisition>();

var graphClient = new GraphServiceClient(
new DelegateAuthenticationProvider(async (request) =>
{
var token = await tokenAcquisition
.GetAccessTokenForUserAsync(Config.Scopes, user: context.Principal);
request.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", token);
})
);

var user = await graphClient.Me.Request()
.Select(u => new
{
u.DisplayName,
u.Mail,
u.UserPrincipalName,
u.MailboxSettings
})
.GetAsync();

context.Principal.AddUserGraphInfo(user);

try
{
var photo = await graphClient.Me
.Photos["48x48"]
.Content
.Request()
.GetAsync();

context.Principal.AddUserGraphPhoto(photo);
}
catch (ServiceException ex)
{
if (ex.IsMatch("ErrorItemNotFound") ||
ex.IsMatch("ConsumerPhotoIsNotSupported"))
{
context.Principal.AddUserGraphPhoto(null);
}
else
{
throw ex;
}
}

options.Events.OnAuthenticationFailed = context => {
var error = WebUtility.UrlEncode(context.Exception.Message);
context.Response
.Redirect($"/Home/ErrorWithMessage?message=Authentication+error&debug={error}");
context.HandleResponse();

return Task.FromResult(0);
};

options.Events.OnRemoteFailure = context => {
if (context.Failure is OpenIdConnectProtocolException)
{
var error = WebUtility.UrlEncode(context.Failure.Message);
context.Response
.Redirect($"/Home/ErrorWithMessage?message=Sign+in+error&debug={error}");
context.HandleResponse();
}

return Task.FromResult(0);
};
};
})
.EnableTokenAcquisitionToCallDownstreamApi(options =>
{
Configuration.Bind("AzureAd", options);
}, Config.Scopes)
.AddMicrosoftGraph(options =>
{
options.Scopes = string.Join(' ', Config.Scopes);
});

//services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
// .AddAzureAD(options => Configuration.Bind("AzureAd", options));

services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
}).AddMicrosoftIdentityUI();
services.AddRazorPages();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
}

我对使用 AzureAD 和 MS Graph 非常陌生,我希望有人能告诉我哪里出了问题。

最佳答案

根据你的文档,我得到了结果,但我不知道你为什么会犯这个错误。 enter image description here

根据您的错误消息,您是否忽略了第 5 步enter image description here

如果你只想要完整的样本,可以找到here 。如果您只需要为特定应用程序设置一个租户。1.选择第一个选项。 enter image description here2. enter image description here因此,此处的代码应修改如下。

{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"TenantId": "{set up your own Directory (tenant) ID}",
"CallbackPath": "/signin-oidc"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}

关于azure - ASP.NET Core token 获取异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64507632/

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