我在之前正在运行的应用程序中使用RC更新了ASP.NET 5框架beta-8软件包。在我运行后,在启动过程中发生了下一个错误:
InvalidOperationException:没有配置身份验证处理程序来处理该方案:自动 Microsoft.AspNet.Http.Authentication.Internal.DefaultAuthenticationManager.d__12.MoveNext()
var defaultPolicy =
new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
services.AddMvc(setup =>
{
setup.Filters.Add(new AuthorizeFilter(defaultPolicy)); // Error occurs here
});
如果有人有类似的问题,我会感谢您对可能出错的想法或解决方案。此异常的解释也很受欢迎。
Startup.cs
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc.Filters;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.PlatformAbstractions;
using SuperUserMVC.Configuration;
using SuperUserMVC.Extensions;
using SuperUserMVC.GlobalModules;
using System;
namespace SuperUserMVC
{
public class Startup
{
public IConfigurationRoot Configuration { get; set; }
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
var builder = new ConfigurationBuilder()
.SetBasePath(appEnv.ApplicationBasePath)
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
}
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettingsBase>(Configuration.GetSection("AppSettingsBase"));
services.Configure<ConnectionString>(Configuration.GetSection("ConnectionString"));
services.AddSqlServerCache(cache =>
{
cache.ConnectionString = Configuration.Get<string>("ASPState:ConnectionString");
cache.SchemaName = Configuration.Get<string>("ASPState:Schema");
cache.TableName = Configuration.Get<string>("ASPState:Table");
});
services.AddSession(session =>
{
session.IdleTimeout = TimeSpan.FromMinutes(120);
});
// Only allow authenticated users.
var defaultPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
// Add MVC services to the services container.
services.AddMvc(setup =>
{
setup.Filters.Add(new AuthorizeFilter(defaultPolicy));
});
var builder = new ContainerBuilder();
builder.RegisterModule(new AutofacModule());
builder.Populate(services);
var container = builder.Build();
return container.Resolve<IServiceProvider>();
}
public void Configure(IApplicationBuilder app, IHttpContextAccessor httpContextAccessor)
{
// Catch unhandled exception in pipeline.
bool isProductionEnvironment = Configuration.Get<bool>("environmentVariables:isProductionEnvironment");
app.UseCustomUnhandledException(isProductionEnvironment, Configuration.Get<string>("defaultErrorPagePath"));
// Log requests.
app.UseVisitLogger(isProductionEnvironment);
// Session must be used before MVC routes.
app.UseSession();
// Configure the HTTP request pipeline.
app.UseCookieAuthentication(options =>
{
options.AuthenticationScheme = "Cookies";
options.LoginPath = new PathString("/Account/Login/");
options.AccessDeniedPath = new PathString("/Account/Forbidden/");
options.CookieName = "MyCookie";
options.AutomaticAuthenticate = true;
options.SessionStore = new MemoryCacheSessionStore();
});
AutoMapperInitializer.Init();
app.UseStaticFiles();
// Route configuration.
app.UseMvc(routes =>
{
routes.MapRoute(
name: "AreaDefault",
template: "{area:exists=Demo}/{controller=Home}/{action=Index}/{id?}"
);
routes.MapRoute(
name: "Default",
template: "{controller=Home}/{action=Index}/{id?}"
);
});
}
}
}
答案 0 :(得分:49)
希望这会对其他人有所帮助,因为我花了很多时间来处理这个错误,即使我设置了AutomaticChallenge = true
。
如果您将app.UseIdentity();
放在app.UseMvc(routes => ...)
之后,则会出现同样的错误。现在我知道答案很明显了。这是因为所有这些中间件都按照您添加它的顺序发生。
这会导致&#34; 没有配置身份验证处理程序&#34;错误:
public void Configure(...)
{
app.UseMvc(routes => { routes.MapRoute(...) }; );
app.UseIdentity();
}
这不会导致错误:
public void Configure(...)
{
app.UseIdentity();
app.UseMvc(routes => { routes.MapRoute(...); });
}
答案 1 :(得分:28)
尝试在Cookie选项中设置options.AutomaticChallenge = true;
,它应该有效。
options.AutomaticAuthentication
分为options.AutomaticAuthenticate
和options.AutomaticChallenge
。如果最后一个留给false
,则抛出异常,因为没有身份验证中间件处理授权过滤器应用的质询。
答案 2 :(得分:20)
将其放在Configure方法上。
app.UseIdentity();
答案 3 :(得分:6)
通过确保cookie方案在引用的任何地方始终被命名,我解决了这个问题。 e.g:
public void ConfigureServices(IServiceCollection services)
{
// if using IdentityServer4
var builder = services.AddIdentityServer(options =>
{
options.AuthenticationOptions.AuthenticationScheme = Constants.DefaultCookieAuthenticationScheme;
...
})
services.AddIdentity<MyUser, IdentityRole>(options =>
{
options.Cookies.ApplicationCookie.AuthenticationScheme = Constants.DefaultCookieAuthenticationScheme;
...
}
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = Constants.DefaultCookieAuthenticationScheme,
AutomaticAuthenticate = false,
AutomaticChallenge = true
});
}
与身份验证中间件交互时。 e.g:
await HttpContext.Authentication.SignInAsync(Constants.DefaultCookieAuthenticationScheme, cp);
答案 4 :(得分:3)
如果您使用app.UseIdentity();
和其他一些登录中间件,例如UseFacebookAuthentication
,请确保app.UseFacebookAuthentication()
在app.UseIdentity();
之后。
答案 5 :(得分:2)
另一种可能性是在配置
中缺少以下设置app.UseCookieAuthentication();
答案 6 :(得分:0)
虽然很有可能将我们的大部分配置设置放在startup.cs
文件中,但似乎首选的方法是设置app.UseCookieAuthentication()
- sans选项 - startup.cs
文件,然后放置所有&#39;选项&#39;和单独文件中的其他细节。
类似于我们在处理Global.asax
文件如何指向Asp.Net vBefore中App_Start
文件夹文件的方式。
尝试在startup.cs
中配置EF / Sql时,我遇到了类似的痛苦,并且移动了所有选项&#39;在startup.cs
之外,事情变得更好。
另外:请注意Fredy Wenger对您的问题的评论,该评论指出了重命名&#39;从v -8beta到v -RC1-final的许多名称空间。