Microsoft Learn

Implementing Authentication in ASP.NET Core MVC

Authentication is the process of verifying the identity of a user. In ASP.NET Core, authentication is handled by a middleware pipeline that can be configured to support various authentication schemes, such as cookies, JWT Bearer tokens, OAuth, and OpenID Connect.

Understanding Authentication Middleware

The ASP.NET Core authentication system is designed to be flexible and extensible. At its core are:

  • Authentication Handlers: These are responsible for specific authentication schemes. For example, the cookie authentication handler processes authentication tickets stored in cookies.
  • Authentication Schemes: A named configuration that defines how authentication should be performed for a particular request.
  • IAuthenticationService: An interface that provides methods for authenticating users.

You configure authentication services in your application's Program.cs (or Startup.cs in older versions) file using methods like AddAuthentication() and AddCookie().

Cookie Authentication

Cookie authentication is a common scheme for web applications. It involves:

  1. The user logs in with credentials.
  2. The application verifies the credentials.
  3. If successful, the application creates an authentication ticket.
  4. The ticket is serialized and stored in a cookie that is sent to the browser.
  5. On subsequent requests, the cookie is sent back to the server. The cookie authentication handler deserializes the ticket, validates it, and establishes the user's identity.

To enable cookie authentication, you typically add it like this:


// Program.cs
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
    options.LoginPath = "/Account/Login"; // The path to your login page
    options.LogoutPath = "/Account/Logout"; // The path to your logout page
});

builder.Services.AddControllersWithViews();

var app = builder.Build();

// ... other middleware setup

app.UseAuthentication(); // Must be called before UseAuthorization()
app.UseAuthorization();

// ...
                

Creating Login and Logout Pages

You'll need MVC controllers and views to handle the login and logout processes. The login controller action will typically:

  • Accept username and password.
  • Validate the credentials (e.g., against a database).
  • If valid, create a ClaimsPrincipal representing the authenticated user.
  • Sign in the user using HttpContext.SignInAsync().

The logout controller action will simply call HttpContext.SignOutAsync().

Important: Ensure that app.UseAuthentication(); is called before app.UseAuthorization(); in your request pipeline configuration.

Protecting Actions with [Authorize] Attribute

Once authentication is set up, you can protect specific controller actions or entire controllers by applying the [Authorize] attribute.


using Microsoft.AspNetCore.Authorization;

[Authorize]
public class DashboardController : Controller
{
    public IActionResult Index()
    {
        // This action is only accessible to authenticated users
        return View();
    }
}

public class HomeController : Controller
{
    [AllowAnonymous] // This action is accessible to everyone
    public IActionResult Index()
    {
        return View();
    }

    // Requires authentication
    public IActionResult About()
    {
        return View();
    }
}
                

Working with Claims

When a user is authenticated, their identity is represented by a ClaimsPrincipal, which contains a collection of Claims. Claims represent pieces of information about the user, such as their name, email, or roles.

You can access claims in your controllers or views:


// In a Controller action
var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
var userName = User.Identity?.Name;
var userRoles = ((ClaimsIdentity)User.Identity).Claims
                    .Where(c => c.Type == ClaimTypes.Role)
                    .Select(c => c.Value);
                

This provides a powerful mechanism for managing user information and permissions.

External Authentication Providers (OAuth/OpenID Connect)

ASP.NET Core also makes it straightforward to integrate with external authentication providers like Google, Facebook, Microsoft accounts, etc., using OAuth 2.0 and OpenID Connect. This is achieved by adding specific authentication extensions, such as AddGoogle(), AddFacebook(), etc., to the authentication services configuration.

This allows users to log in using their existing accounts, improving user experience and reducing the need for them to create new credentials.

Next Steps

Now that you understand the basics of authentication, explore how to implement Authorization to control what authenticated users can do within your application.