Redirect Non-Authenticated Users to Login - ASP.NET 5 & Core
Update: Steps also work in .NET 5.
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 to this problem is easier than expected, you simply need to add the below snippet to your ConfigureServices method within the startup.cs file.
// This pushes users to login if not authenticated
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.
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.
public IActionResult Index()
You also need to make sure that your controller references the Microsoft.AspNetCore.Authorization package.
I hope this helps you to redirect users to the login page if they are not authenticated.