ASP.NET Restrict access to controller methods and views’ contents based on authentification status

You can restrict the access to any controller method using the [Authorize] attribute, which is the part of the Microsoft.AspNetCore.Authorization namespace. For instance, in the example below the method About of the HomeController can be accessed only by authenticated users.

using Microsoft.AspNetCore.Authorization;

public class HomeController : Controller
{
    [Authorize]
    public IActionResult About()
    {
        ViewData["Message"] = "Your application description page.";
        return View();
    }
}

Additionally, you can filter the content of a view based on the authentification status of the user employing the IsAuthenticated property of the Identity class. The Identity class is part of the User class. In the example below, the authenticated users will have three buttons in the header (Home, About, and Contact), while the non-authenticated user will see only one button (Home).

@if (User.Identity.IsAuthenticated)
{
    <ul class="nav navbar-nav">
        <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
        <li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li>
        <li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>
    </ul>
}
else
{
    <ul class="nav navbar-nav">
        <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
    </ul>
}