Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

I cant seem to get it to work, currently the user just gets a blank page.

Below is my ConfigureServices method in Startup.cs

        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>();
    }
like image 805
Mike U Avatar asked Jan 05 '23 20:01

Mike U


2 Answers

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://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity-configuration?view=aspnetcore-2.1#cookie-settings

like image 65
Jawand Singh Avatar answered Jan 13 '23 10:01

Jawand Singh


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;
    }
like image 25
Mariano Soto Avatar answered Jan 13 '23 10:01

Mariano Soto