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

5
我正在使用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>();
    }
5个回答

4

我仍然无法将用户重定向到登录页面(如果未登录)。我尝试在主要的Startup.cs和IdentityHostingStartup.cs中添加上述代码,但都不起作用。我错过了什么?顺便说一下,我正在使用Core 3.1。 - Mocas
谢谢。如果您之前更改了登录网址,请确保更改LoginPath。对我来说,我必须将路径从“/Identity/Account/Login”更改为“/login”。 - Ben

3
同样的问题在这里。在这个问题解决之前,可以采取以下快速解决方法:
public class LogInRequiredFilter : IAuthorizationFilter 
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        if (!AttributeManager.HasAttribute(context, typeof(LogInRequired))) return;

        if (context.HttpContext.User.Identity.IsAuthenticated) return;

        context.Result = new RedirectResult("/login?ReturnUrl=" + Uri.EscapeDataString(context.HttpContext.Request.Path));
    }

}

public class LogInRequired : Attribute
{
    public LogInRequired()
    {

    }
}

然后在你的控制器中:

    [HttpGet, LogInRequired]
    public IActionResult 
        return View();
    }

这将会把你重定向到登录页面,并在登录后将你重定向回原本想要访问的页面。
属性管理器代码:
public static Boolean HasAttribute(AuthorizationFilterContext context, Type targetAttribute)
    {
        var hasAttribute = false;
        var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
        if (controllerActionDescriptor != null)
        {
            hasAttribute = controllerActionDescriptor
                                            .MethodInfo
                                            .GetCustomAttributes(targetAttribute, false).Any();
        }

        return hasAttribute;
    }

2
AttributeManager来自哪里?这个有没有不同的库? - Rob
抱歉耽搁了。这是一个自定义类,用于检查操作是否具有属性。答案已更新。 - Mariano Soto

2
我刚刚也在处理这个问题,得出结论是最新版本的“Microsoft.AspNetCore.Identity.EntityFrameworkCore”依赖项存在问题。 我最初使用的是版本1.1.0,但经过大量调试、owin中间件记录等操作后,我得出了结论:我没有做错任何事情。我进行了检查:
  • Authorize attribute worked and blocked the request
  • Added event handlers (OnRedirectToLogin) as below to verify the redirect URL (this was only for debugging)

    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);
        }
    };     
    

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

options.Cookies.ApplicationCookie.LoginPath = new PathString("/Auth/Login");

澄清一下,这个版本是可以工作的: Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.0.1"

我将提交一个错误报告给ASPNETCORE团队进行调查,关于1.1.0版本的问题。


0

0

仅为完整性而言 - 建议使用以下代码块来补充@Jawand的答案:

        services.ConfigureApplicationCookie(options => {
            options.AccessDeniedPath = "/Identity/Account/AccessDenied";
            options.Cookie.Name = "YourAppCookieName";
            options.Cookie.HttpOnly = true;
            options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
            options.LoginPath = "/Identity/Account/Login";
            // ReturnUrlParameter requires 
            //using Microsoft.AspNetCore.Authentication.Cookies;
            options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
            options.SlidingExpiration = true;

        });

1
我仍然无法将用户重定向到登录页面(如果未登录)。我尝试在主要的Startup.cs和IdentityHostingStartup.cs中添加上述代码,但都不起作用。我错过了什么?顺便说一下,我正在使用Core 3.1。 - Mocas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接