Redirect Non-Authenticated Users to Login - ASP.NET Core 3

Updated on 14th March 2020

Purhaps you want to build a web portal or some kind of webapp for a select group of people, something that's only accessable by authenticated users who have logged in.

This is exactly what I needed to build a little while ago.

I'm using ASP.NET Core 3 with Identity to manage my users and I wanted to redirect anyone to the login page if they are not already logged in.

The solution

The solution to this problem is easier than expected, you simply need to add the below snippet to your ConfigureServices method within the startup.cs file.

services.AddMvc(options =>
    {
        // This pushes users to login if not authenticated
        options.Filters.Add(new AuthorizeFilter());
    });

This is assuming that you're using Identity to manage your users and the MVC middleware. Also make sure that you're using the MVC.Authorization package within your startup.cs file.

using Microsoft.AspNetCore.Mvc.Authorization;

The Override

If you need to exclude any pages from being redirected to the login page, for example if you want people to have access to the home page without logging in. Simply add the the AllowAnonymous attribute to the controller action.

[AllowAnonymous]
public IActionResult Index()
{
    return View();
}

You also need to make sure that your controller references the Microsoft.AspNetCore.Authorization package.

using Microsoft.AspNetCore.Authorization;

I hope this helps you to redirect users to the login page if they are not authenticated.


Article Categories: # .net # c# # identity

About

A tech blog by Andy P. I talk about coding, enterprise software development, tech, games design & other things that interest me.

Signup To The Newsletter

I try to post a new interesting article every saturday.