ASP.Net core MVC6 未授权时重定向到登录

Mik*_*e U 5 c# asp.net-mvc asp.net-core-mvc .net-core

我正在使用 ASP.Net core MVC 6,如果用户未经过身份验证,我试图将用户重定向到登录页面。

我似乎无法让它工作,目前用户只得到一个空白页面。

下面是我在 Startup.cs 中的 ConfigureServices 方法

        public void ConfigureServices(IServiceCollection services) {
        // Add framework services.
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
        );

        services.AddIdentity<ApplicationUser, IdentityRole>(options => {
            // configure identity options
            options.Password.RequireDigit = true;
            options.Password.RequireLowercase = true;
            options.Password.RequireUppercase = true;
            options.Password.RequireNonAlphanumeric = true;
            options.Password.RequiredLength = 7;

            options.Cookies.ApplicationCookie.AutomaticAuthenticate = true;
            options.Cookies.ApplicationCookie.AutomaticChallenge = true;
            options.Cookies.ApplicationCookie.LoginPath = "/Account/Login";

            // User settings
            options.User.RequireUniqueEmail = true;
        })
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.AddMvc();

        // Add application services.
        services.AddTransient<IEmailSender, AuthMessageSender>();
        services.AddTransient<ISmsSender, AuthMessageSender>();
    }
Run Code Online (Sandbox Code Playgroud)

mar*_*p86 2

我自己只是在努力解决这个问题,我得出的结论是,最新版本的“Microsoft.AspNetCore.Identity.EntityFrameworkCore”依赖项似乎存在问题

我最初使用的是 1.1.0 版本,但经过大量调试、owin 中间件日志记录等后,我得出的结论是我没有做错任何事情。我检查了:

  • 授权属性有效并阻止了请求
  • 添加了如下事件处理程序 (OnRedirectToLogin) 以验证重定向 URL(这仅用于调试)

    options.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents
    { 
        OnRedirectToLogin = evt => {
            evt.Response.Redirect(evt.RedirectUri); // this url is correct, but the redirect never happens!??
            return Task.FromResult(0);
        }
    };     
    
    Run Code Online (Sandbox Code Playgroud)

解决方案:我将包回滚到版本 1.0.1,然后按预期启动重定向 - 重定向到 LoginPath 设置中 Startup.cs 中定义的 URL

options.Cookies.ApplicationCookie.LoginPath = new PathString("/Auth/Login");
Run Code Online (Sandbox Code Playgroud)

澄清一下,这个版本有效:Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.0.1"

我将向 ASPNETCORE 团队提出一个有关 1.1.0 版本的错误以进行调查。