ASP.Net core MVC6 Redirect to Login when not authorised

前端 未结 4 657
南旧
南旧 2021-01-13 20:25

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.

I cant seem to get it to work, currently the u

相关标签:
4条回答
  • 2021-01-13 20:53

    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.

    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. 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)

      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

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

    To clarify, THIS version works: 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.

    0 讨论(0)
  • 2021-01-13 21:07

    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;
        }
    
    0 讨论(0)
  • 2021-01-13 21:07

    Just for completeness - the following code block is suggested to fill out @Jawand's answer:

            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;
    
            });
    
    0 讨论(0)
  • 2021-01-13 21:16

    OK, as of 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.

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

    for more info visit Microsoft identity documentation. https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity-configuration?view=aspnetcore-2.1#cookie-settings

    0 讨论(0)
提交回复
热议问题