无法获取 .net 核心 MVC 以将 401 重定向到 /帐户/登录



当我请求[授权]装饰的控制器操作而不是重定向到登录页面时,我会收到401错误。

这是使用IIS Express上运行的身份模板的.NET Core MVC应用。

当我从program.cs运行该应用时,重定向到登录工作正常。我添加了明确的方向,以使Cookie身份验证使用/帐户/登录重定向以进行配置和服务部分,并配置身份以执行此重定向。

我无法正常工作。以下是我的创业课,我应该更改它以使其在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);
    }
}

我整夜都有同样的问题,找不到解决方案。直接从kestrel重定向罚款,但是通过IIS或II Express根本不会重定向 - 它将转到白页。

发布到身份git之后,我意识到我的模板已设置为在框架的1.0.1下运行,而不是1.1.0。我将其更新为使用1.1.0,并将所有Nuget软件包更新为1.1.0,现在它在IIS和IIS中正常转移。

我不确定包装更新是否"修复"了某些螺旋式的东西,或者这只是1.0.1的问题,该问题已固定在1.1.0中。

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

身份自动添加cookie身份验证。您正在第二次添加配置。

当您添加第二个实例时,您将两个自动属性都设置,因此现在有两个中间件试图进行重定向,并且该行为是"不确定的"(其中undefined =="要严重弄乱事物")。

Startup类中的Configure方法中的此行,解决我问题:

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

相关内容

  • 没有找到相关文章

最新更新