ASP.NET 5 & Core Identity - Authorize and AllowAnonymous

Published on

In my last blog post, I talked about how you can redirect non-authenticated users to the login page in ASP.NET 5 & Core 3 using Identity.

But what if you want to exclude some pages from the redirect?

Your site may have a landing page or informational page that any anonymous user should be grented access to view.

Essentially we want to have a flag that can be specified on a page-by-page basis that overrides the Identity settings in the startup.cs file, always allowing non-authenticated users to access a page(s) that we choose.

This kind of extra control can be achieved with the [Authorize] and the [AllowAnonymous] attributes.

Using [AllowAnonymous] to allow access for all users

Firstly, add a reference to the Microsoft.AspNetCore.Authorization package to the top of the controller. You may need to download the nuget package first.

using Microsoft.AspNetCore.Authorization;

In the standard ASP.NET Core 3 MVC template, the method for the index page looks like this before we make any changes;

public IActionResult Index()
{
  return View();
}

We can add the [AllowAnonymous] attribute to the HomeController class OR the Index method.

[AllowAnonymous]
public class HomeController : Controller
{
 [AllowAnonymous]
  public IActionResult Index()
  {
    return View();
  }
}

Applying the attribute to the class will grant non-authenticated users the ability to access any of the pages within the controller, while applying the attribute to the method will only grant access to the individual page.

You'd typically use this attribute on the Index, Login or Registration pages of your website, however it depends on your specific use case.

Using [Authorize] to restrict access

[Authorize] works in the opposite way to the [AllowAnonymous] attribute.

We might not have any Identity redirects setup in the startup.cs file, but we want to restrict access to a specific page to authenticated users only!

In the same way we use the [AllowAnonymous] attribute, just apply the [Authorize] attribute on the controller or view.

For example;

[Authorize]
public class HomeController : Controller
{
  [Authorize]
  public IActionResult Index()
  {
    return View();
  }
}

Article Categories: # .net # c# # identity
Date Published: Feb 29, 2020

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.

IT Asset Management

Our friends at AssetPad are building a complete online solution for managing the IT assets within your organisation. With barcodes and documentation tools.