简体   繁体   English

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

[英]ASP.Net core MVC6 Redirect to Login when not authorised

I am using ASP.Net core MVC 6, I am trying to get the user redirected to the login page if they are not authenticated.我正在使用 ASP.Net 核心 MVC 6,如果用户未经身份验证,我试图让用户重定向到登录页面。

I cant seem to get it to work, currently the user just gets a blank page.我似乎无法让它工作,目前用户只是得到一个空白页面。

Below is my ConfigureServices method in Startup.cs下面是我在 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>();
    }

OK, as of Asp.Net Core 2.1 .好的,从 Asp.Net Core 2.1 开始。 In order to redirect user to login page.为了将用户重定向到登录页面。 this is what you need to do in ConfigureServices(IserviceCollection services) method.这是您需要在ConfigureServices(IserviceCollection services)方法中执行的操作。

services.ConfigureApplicationCookie(options =>
{
    options.LoginPath = "/Identity/Account/Login";
    options.SlidingExpiration = true;
});

for more info visit Microsoft identity documentation.有关详细信息,请访问 Microsoft 标识文档。 https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity-configuration?view=aspnetcore-2.1#cookie-settings https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity-configuration?view=aspnetcore-2.1#cookie-settings

Same problem here.同样的问题在这里。 A quick fix while this problem is solved:解决此问题时的快速修复:

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()
    {

    }
}

And then in your controller:然后在您的控制器中:

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

This will redirect you to your login page and afterwards it redirects you to the original page you wanted to access.这会将您重定向到您的登录页面,然后将您重定向到您想要访问的原始页面。

Attribute manager code:属性管理器代码:

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

I was just wrestling with this myself and I've come to the conclusion that there seems to be an issue in the latest version of the "Microsoft.AspNetCore.Identity.EntityFrameworkCore" dependency .我自己只是在纠结这个,我得出的结论是,最新版本的“Microsoft.AspNetCore.Identity.EntityFrameworkCore”依赖项似乎存在问题

I was originally using version 1.1.0 but after lots of debugging, owin middleware logging etc, I came to the conclusion that I wasn't doing anything wrong.我最初使用的是 1.1.0 版,但经过大量调试、owin 中间件日志记录等之后,我得出的结论是我没有做错任何事情。 I checked:我检查了:

  • Authorize attribute worked and blocked the request授权属性有效并阻止了请求
  • Added event handlers (OnRedirectToLogin) as below to verify the redirect URL (this was only for debugging)添加如下事件处理程序 (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); } };

The resolution : I rolled back my package to the version 1.0.1 and then the redirects kicked in as expected - to the URL defined in Startup.cs in the LoginPath setting解决方案:我将我的包回滚到 1.0.1 版,然后重定向按预期启动 - 到 LoginPath 设置中 Startup.cs 中定义的 URL

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

To clarify, THIS version works: Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.0.1"澄清一下,此版本有效: Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.0.1"

I'm going to raise a bug with the ASPNETCORE team for investigation as regards to the 1.1.0 version.我将向 ASPNETCORE 团队提出一个关于 1.1.0 版本的错误进行调查。

Just for completeness - the following code block is suggested to fill out @Jawand's answer:只是为了完整性 - 建议使用以下代码块来填写@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;

        });

In order to extend IdentyUser to ApplicationUser, you need to follow Microsoft's directions.为了将 IdentyUser 扩展到 ApplicationUser,您需要遵循 Microsoft 的指示。 I had this exact problem that you are experiencing, I partially did what Microsoft instructed me to do and as a result, I would get access denied when a user did not have access to a method.我遇到了您遇到的这个确切问题,我部分地执行了 Microsoft 指示我做的事情,因此,当用户无法访问某个方法时,我会被拒绝访问。 https://docs.microsoft.com/en-us/aspnet/core/security/authentication/customize-identity-model?view=aspnetcore-5.0 https://docs.microsoft.com/en-us/aspnet/core/security/authentication/customize-identity-model?view=aspnetcore-5.0

You have to add all navigation properties.您必须添加所有导航属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM