无法让 .net 核心 MVC 将 401 重定向到 /Account/Login

Can't get .net core MVC to redirect 401 to /Account/Login

当我请求经过 [Authorize] 修饰的控制器操作而不是被重定向到登录页面时,我收到 401 错误。

这是在 IIS Express 上使用标识模板 运行ning 的 .net 核心 mvc 应用程序。

当我 运行 来自 program.cs 的应用程序时,重定向到登录工作正常。 我已经为 cookie 身份验证添加了明确的说明,以便为配置和服务部分使用 /Account/Login 重定向,以及配置身份以执行此重定向。

我无法让它工作。下面是我的 StartUp class,我应该更改什么才能使其在 IIS express 中运行?:

public class Startup
{
    private MapperConfiguration _mapperConfiguration { get; set; }

    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

        if (env.IsDevelopment())
        {
            // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
            builder.AddUserSecrets();
        }

        builder.AddEnvironmentVariables();
        Configuration = builder.Build();

        _mapperConfiguration = new MapperConfiguration(cfg =>
        {
            cfg.AddProfile(new AutoMapperProfileConfiguration());
        });
    }

    public IConfigurationRoot Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));


        services.AddIdentity<ApplicationUser, IdentityRole>(
            option => {
                option.Cookies.ApplicationCookie.LoginPath = "/Account/Login";
                option.Cookies.ApplicationCookie.AutomaticChallenge = true;
                option.Cookies.ApplicationCookie.AutomaticAuthenticate = true;
            })
            .AddEntityFrameworkStores<ApplicationDbContext>();

        services.AddDataProtection();

        services.AddMvc();
        services.AddSignalR();

        // Add application services.
        services.AddTransient<IEmailSender, AuthMessageSender>();
        services.AddTransient<ISmsSender, AuthMessageSender>();
        services.Configure<AuthMessageSenderOptions>(Configuration);
        services.Configure<IISOptions>(options => options.AutomaticAuthentication = true);
        services.AddSingleton<IMapper>(sp => _mapperConfiguration.CreateMapper());
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApplicationDbContext context, RoleManager<IdentityRole> roleManager)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();



        app.UseStaticFiles();

        app.UseIdentity();

        // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715

        //app.UseStatusCodePagesWithReExecute("/Home/Error/{0}");

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationScheme = "MyCookies",
            SlidingExpiration = true,
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            LoginPath = new PathString("/Account/Login")
        });
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
            routes.MapRoute(
                name: "index",
                template: "{controller=Home}/{id?}",
                defaults: new { action = "Index" });
        });
        app.UseSignalR();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        MyDbInit.Init(context, roleManager);

    }
}

Identity自动添加cookie认证。您将在 Configure 中第二次添加它。

当您添加第二个实例时,您设置了两个自动属性,所以现在两个中间件正在尝试进行重定向,并且该行为是 "undefined"(其中 undefined == "Going to seriously mess things up" ).

我整晚都遇到同样的问题,但找不到解决方案。 运行 直接从 Kestrel 重定向的站点很好,但是通过 IIS 或 IIS Express 它根本不会重定向 - 它会转到白页。

发到IdentityGit后才发现我的模板是运行框架1.0.1下设置的,不是1.1.0。我将其更新为使用 1.1.0 并将所有 Nuget 包更新为 1.1.0,现在它在 IIS 和 IIS Express 中正确重定向。

我不确定软件包更新 "fixed" 是否有问题,或者这只是 1.0.1 的问题,已在 1.1.0 中修复。

https://blogs.msdn.microsoft.com/webdev/2016/11/16/announcing-asp-net-core-1-1/

Startup class 中 Configure 方法中的这一行,解决我的问题:

public class Startup
{
     public void Configure(IApplicationBuilder app, IHostingEnvironment env)
     {
         ...
         app.UseAuthentication(); // <= This line
         app.UseMvc(routes =>
         {
            ...
         });
     }
}