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

问题描述 投票:0回答:3

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

这是一个使用IIS Express上运行的身份模板的.net核心mvc应用程序。

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

我无法让它发挥作用。下面是我的StartUp类,我应该更改什么才能使它在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);

    }
}
redirect asp.net-identity asp.net-core-mvc iis-express http-status-code-401
3个回答
7
投票

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

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

我不确定软件包是否更新了“固定”的东西,如果这只是一个问题,而且只是1.1.1中修复的问题。

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


1
投票

Identity会自动添加cookie身份验证。您将在Configure中再次添加它。

当您添加第二个实例时,您正在设置两个自动属性,所以现在两个中间件正在尝试进行重定向,并且该行为是“未定义”(其中undefined ==“严重搞乱”)。


0
投票

Configure类的Startup方法里面的这行,解决了我的问题:

public class Startup
{
     public void Configure(IApplicationBuilder app, IHostingEnvironment env)
     {
         ...
         app.UseAuthentication(); // <= This line
         app.UseMvc(routes =>
         {
            ...
         });
     }
}
© www.soinside.com 2019 - 2024. All rights reserved.