23

I updated ASP.NET 5 framework beta-8 packages with RC ones on previously working application. After I got it running next error occured in the startup process:

InvalidOperationException: No authentication handler is configured to handle the scheme: Automatic 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
});

If anyone had similar problem, I'd appreciate your idea or solution on what might have gone wrong. Explanation of this exception is also appreciated.

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?}"
                );
            });
        }
    }
}
1
  • I have just started to develop with asp.net with the last beta (created a new project and then enhanced it a bit) and also had problems after update to RC, because they have changed various BASE-things. Unfortunately I don't have found any description, how to change existing projects to be compatible. So... I then have recreated my project from scratch from a new template, to be fully compatible. As RC is is supported for production by MS, I think (hope so) there don't will be such changes in the future (release version Q1 2016). Nov 20, 2015 at 11:30

7 Answers 7

49

Hopefully this will help somebody else because I just spent a lot of time dealing with this error even though I had set AutomaticChallenge = true.

Turns out you will get the same error if you put app.UseIdentity(); after app.UseMvc(routes => ...). Now that I know the answer it's obvious. It's because all this middleware happens in the order you add it.

This causes the "No authentication handler is configured" error:

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

        app.UseIdentity();
    }

This does not cause the error:

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

        app.UseMvc(routes => { routes.MapRoute(...); });
    }
3
  • 2
    Thanks. The same seems to apply to Uapp.UseOpenIdConnectAuthentication() and app.UseCookieAuthentication() Apr 29, 2016 at 12:58
  • 1
    After one year still valid for me. Thx
    – Mariusz
    Jan 15, 2017 at 19:23
  • My error was this ordering of calls (since I was mocking authentication for integration testing). I would never have guessed it! Thanks!
    – Vetras
    Feb 20, 2017 at 15:47
27

Try setting options.AutomaticChallenge = true; in your cookies options and it should work.

options.AutomaticAuthentication was split into options.AutomaticAuthenticate and options.AutomaticChallenge. If the last one is left to false, an exception is thrown because no authentication middleware handles the challenge applied by the authorization filter.

3
  • 4
    What if your not using Cookies? Oct 17, 2016 at 5:54
  • 1
    @AlexHopeO'Connor, I set it directly to Google authentication options Jan 25, 2017 at 4:26
  • 12
    There is no options.AutomaticChallenge in asp.net core 2.0 Sep 21, 2017 at 23:22
19

Put this on Configure method.

        app.UseIdentity();
1
  • I think you mean Configure, not ConfigureServices.
    – Peter
    Sep 8, 2016 at 13:53
6

The problem was solved for me by making sure the cookies scheme was consistently named wherever it was referenced. 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
    });
}

And when interacting with the authentication middleware. e.g.:

await HttpContext.Authentication.SignInAsync(Constants.DefaultCookieAuthenticationScheme, cp);
1
  • After implementing the first answer regarding "options.AutomaticAuthentication was split into options.AutomaticAuthenticate and options.AutomaticChallenge", I still received the same error, but after replacing the upper-case "Cookies" from the sample to lower case (as it was spelled in another place), my app started to work! Thank you very much!
    – Papa Stahl
    Mar 15, 2017 at 16:02
3

If you use app.UseIdentity(); and some other login middleware such as UseFacebookAuthentication make sure app.UseFacebookAuthentication() is AFTER app.UseIdentity();.

1
2

another possibility is missing the following setting in Configure

app.UseCookieAuthentication();
1
  • This is now obsolete Mar 29, 2018 at 14:19
0

While it's tempting to place much of our configuration settings within the startup.cs file, it seems that the preferred way of doing things is to set your app.UseCookieAuthentication() - sans options - within the startup.cs file, and then place all of the 'options' and other details within a separate file.

Sort of like what we were doing with how the Global.asax file had pointers to the App_Start folder files in Asp.Net vBefore.

I suffered similar pain while trying to configure EF/Sql in the startup.cs, and by moving all 'options' outside of startup.cs things worked much better.

ALSO: take note of the Fredy Wenger comment to your question that points out the 'renaming' of many of the namespaces from v -8beta to v -RC1-final.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.