ASP.NET Core Authentication

Overview

Authentication in ASP.NET Core identifies the user making a request. It works in tandem with authorization to determine what resources a user can access.

Getting Started

Setup
Configuration
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

var builder = WebApplication.CreateBuilder(args);

// Add authentication services
builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = "Cookies";
})
.AddCookie("Cookies", opts => 
{
    opts.LoginPath = "/Account/Login";
    opts.AccessDeniedPath = "/Account/AccessDenied";
});

var app = builder.Build();

// Enable authentication middleware
app.UseAuthentication();
app.UseAuthorization();

app.MapGet("/", () => "Hello Secure World!").RequireAuthorization();

app.Run();
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "Authentication": {
    "Schemes": {
      "Cookies": {
        "LoginPath": "/Account/Login",
        "LogoutPath": "/Account/Logout",
        "ExpireTimeSpan": "00:30:00"
      }
    }
  }
}

Code Example: Login Page

public class AccountController : Controller
{
    private readonly SignInManager<IdentityUser> _signInManager;

    public AccountController(SignInManager<IdentityUser> signInManager)
    {
        _signInManager = signInManager;
    }

    [HttpGet]
    public IActionResult Login(string returnUrl = "/")
    {
        ViewData["ReturnUrl"] = returnUrl;
        return View();
    }

    [HttpPost]
    public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = "/")
    {
        if (!ModelState.IsValid) return View(model);

        var result = await _signInManager.PasswordSignInAsync(
            model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);

        if (result.Succeeded)
        {
            return Redirect(returnUrl);
        }

        ModelState.AddModelError(string.Empty, "Invalid login attempt.");
        return View(model);
    }

    [HttpPost]
    public async Task<IActionResult> Logout()
    {
        await _signInManager.SignOutAsync();
        return RedirectToAction("Index", "Home");
    }
}

Common Authentication Schemes

SchemeUse Case
CookieTraditional web apps with server‑side sessions
JwtBearerAPIs and SPA authentication
OpenIdConnectExternal providers (Google, Azure AD)
OAuth2Resource server scenarios
NegotiateWindows Integrated Authentication

FAQ

How do I protect a single Razor page?

Use the @attribute [Authorize] directive at the top of the .cshtml file.

Can I use multiple authentication schemes simultaneously?

Yes. Register each scheme and specify DefaultChallengeScheme or use the [Authorize(AuthenticationSchemes = "SchemeA,SchemeB")] attribute.

What is the difference between authentication and authorization?

Authentication verifies who a user is; authorization determines what the authenticated user can do.