我有一个使用AzureAD和MS Graph的.NET Core 3.1 Web应用程序。
当我第一次调试时,我成功地验证了自己的身份,应用程序的工作与预期的一样,但如果我通过visual studio重新启动调试,我得到以下错误信息。
MsalUiRequiredException : No account or login hint was passed to the AcquireTokenSilent call.
和
Value cannot be null. (Parameter 'accountIdentifier')
与此同时,我可以看到,我是认证,但我的帐户是没有检索以下一行代码。
IAccount account = await application.GetAccountAsync(accountIdentifier).ConfigureAwait(false);
这里是服务器的部分日志文件。
fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[1]
An unhandled exception has occurred while executing the request.
System.Exception: An error was encountered while handling the remote login.
---> System.Exception: OpenIdConnectAuthenticationHandler: message.State is null or empty.
--- End of inner exception stack trace ---
at Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.HandleRequestAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Dynatrace.OneAgent.Introspection.SessionCaptureMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)
这里是我的启动过程。
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)
{
// Token acquisition service based on MSAL.NET
// and chosen token cache implementation
services.AddMicrosoftIdentityPlatformAuthentication(Configuration)
.AddMsal(Configuration, new string[] { Constants.ScopeUserRead })
.AddInMemoryTokenCaches();
services.AddControllers(options =>
{
options.Filters.AddService<HelpertestActionFilter>();
}).AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
services.AddRazorPages().AddRazorRuntimeCompilation();
services.AddDbContext<PortailRAEContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ApplicationContext")));
services.Configure<GzipCompressionProviderOptions>(options => options.Level = System.IO.Compression.CompressionLevel.Optimal);
services.AddResponseCompression(options =>
{
options.Providers.Add<GzipCompressionProvider>();
});
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.None;
});
services.AddOptions();
services.AddTransient<HelpertestActionFilter>();
// Add Graph
services.AddGraphService(Configuration);
services.AddSingleton<TelemetryConfiguration>();
services.AddMvc(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
services.AddMemoryCache();
services.AddSingleton<ITempDataProvider, CookieTempDataProvider>();
services.AddSession();
}
// 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.UseRewriter(
new RewriteOptions().Add(
context => {
if (context.HttpContext.Request.Path == "/AzureAD/Account/SignedOut")
{
context.HttpContext.Request.Path = "/Home/Index";
}
})
);
app.UseHttpsRedirection();
app.Use((context, next) => {
context.Request.Scheme = "https";
return next();
});
app.UseStaticFiles(new StaticFileOptions
{
OnPrepareResponse =
r =>
{
if (!string.IsNullOrEmpty(r.Context.Request.Query["v"]))
{
r.Context.Response.Headers.Add("cache-control", new[] { "public,max-age=31536000" });
r.Context.Response.Headers.Add("Expires", new[] { DateTime.UtcNow.AddYears(1).ToString("R") }); // Format RFC1123
}
}
});
app.UseRouting();
app.UseSession();
app.UseAuthentication();
app.UseAuthorization();
app.UseResponseCompression();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
app.UseCookiePolicy();
}
}
作为参考,我在6个月前开始了我的项目,使用了一个来自于 此处.当时我使用的是.net core 2.x,但后来我把项目更新到.net core 3.1.除了这个 "bug",项目运行正常。
请注意,我看到10天前有一个问题打开了。此处当样本更新到.net core 3.1时,我将更新我的项目,但我需要一个解决方案,直到样本和Microsoft.Identity.Web出来。但我需要一个解决方案,直到样本和Microsoft.Identity.Web出来。
任何帮助都是感激的!
您会注意到,在 WebApp-OpenIDConnect-DotNet.csproj 中的
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
它的目标是.netcore 3.1框架,所以这个示例应该可以用3.1来工作,等我有一点时间的时候,我会试试这个示例,但我认为既然是当前的示例代码,那就可以用。
我测试后会更新,希望能帮到你。