【问题标题】:No authentication handler is configured to handle the scheme: Automatic没有配置身份验证处理程序来处理该方案:自动
【发布时间】:2015-11-20 11:01:48
【问题描述】:

我在以前工作的应用程序上用 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?}"
                );
            });
        }
    }
}

【问题讨论】:

  • 我刚刚开始使用 asp.net 进行最后一个测试版的开发(创建了一个新项目,然后对其进行了一些改进)并且在更新到 RC 后也遇到了问题,因为他们已经更改了各种 BASE-事物。不幸的是,我没有找到任何描述,如何更改现有项目以使其兼容。所以......然后我从新模板从头开始重新创建我的项目,以完全兼容。由于 MS 支持 RC 进行生产,我认为(希望如此)将来不会有这样的变化(2016 年第一季度发布版本)。

标签: asp.net .net asp.net-core asp.net-core-mvc


【解决方案1】:

希望这对其他人有帮助,因为即使我设置了AutomaticChallenge = true,我也花了很多时间处理这个错误。

如果你把app.UseIdentity(); 放在app.UseMvc(routes =&gt; ...) 之后,你会得到同样的错误。现在我知道了答案,这很明显。这是因为所有这些中间件都是按照你添加它的顺序发生的。

这会导致“未配置身份验证处理程序”错误:

    public void Configure(...)
    {
        app.UseMvc(routes => { routes.MapRoute(...) }; );

        app.UseIdentity();
    }

这不会导致错误:

    public void Configure(...)
    {
        app.UseIdentity();

        app.UseMvc(routes => { routes.MapRoute(...); });
    }

【讨论】:

  • 谢谢。这似乎同样适用于 Uapp.UseOpenIdConnectAuthentication() 和 app.UseCookieAuthentication()
  • 一年后对我仍然有效。谢谢
  • 我的错误是调用的顺序(因为我正在模拟集成测试的身份验证)。我永远也猜不到!谢谢!
【解决方案2】:

尝试在您的 cookie 选项中设置 options.AutomaticChallenge = true;,它应该可以工作。

options.AutomaticAuthentication 被拆分为 options.AutomaticAuthenticateoptions.AutomaticChallenge。如果最后一个留给false,则会抛出异常,因为没有身份验证中间件处理授权过滤器应用的质询。

【讨论】:

  • 如果您不使用 Cookie 会怎样?
  • @AlexHopeO'Connor,我直接设置为谷歌身份验证选项
  • asp.net core 2.0中没有options.AutomaticChallenge
【解决方案3】:

把它放在配置方法上。

        app.UseIdentity();

【讨论】:

  • 我想你的意思是Configure,而不是ConfigureServices
【解决方案4】:

通过确保 cookie 方案在任何被引用的地方都被一致地命名,我解决了这个问题。例如:

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
    });
}

以及在与身份验证中间件交互时。例如:

await HttpContext.Authentication.SignInAsync(Constants.DefaultCookieAuthenticationScheme, cp);

【讨论】:

  • 在实施关于“options.AutomaticAuthentication 的第一个答案被拆分为 options.AutomaticAuthenticate 和 options.AutomaticChallenge”后,我仍然收到相同的错误,但在替换了示例中的大写“Cookies”之后小写(因为它在另一个地方拼写),我的应用程序开始工作!非常感谢!
【解决方案5】:

如果您使用app.UseIdentity(); 和其他一些登录中间件,例如UseFacebookAuthentication,请确保app.UseFacebookAuthentication()app.UseIdentity(); 之后。

【讨论】:

  • 解决了我的问题!
【解决方案6】:

另一种可能性是在配置中缺少以下设置

app.UseCookieAuthentication();

【讨论】:

  • 现在已经过时了
【解决方案7】:

虽然将我们的大部分配置设置放在 startup.cs 文件中很诱人,但似乎首选的做事方式是在 startup.cs 文件中设置您的 app.UseCookieAuthentication() - 无选项 - 然后将单独文件中的所有“选项”和其他详细信息。

有点像我们在 Asp.Net vBefore 中处理 Global.asax 文件如何拥有指向 App_Start 文件夹文件的指针。

我在尝试在 startup.cs 中配置 EF/Sql 时遇到了类似的痛苦,并且通过将所有“选项”移到 startup.cs 之外,效果会好很多。

另外:请注意 Fredy Wenger 对您的问题的评论,该评论指出了许多命名空间从 v -8beta 到 v -RC1-final 的“重命名”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-09
    相关资源
    最近更新 更多