Authorization and Authentication in C# (.NET): A Complete Guide

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Authorization and Authentication in C# (.NET): From Basics to Enterprise Solutions



Web application security is a critical aspect of development, and in the C# (.NET) ecosystem, there is a powerful stack of tools for implementing authentication (user identity verification) and authorization (access rights verification). In this article, we will break down the key approaches: from the built-in ASP.NET Core Identity to flexible solutions based on JWT and OAuth 2.0.



1. ASP.NET Core Identity — Built-in User Management System



ASP.NET Core Identity is a full-featured framework for registration, login, role and password management. It provides ready-made models (User, Role), storage (Entity Framework + SQL Server by default), and middleware.



// Registration in Program.csbuilder.Services.AddDbContext<AppDbContext>(options =>    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

builder.Services.AddDefaultIdentity<IdentityUser>(options =>{ options.SignIn.RequireConfirmedAccount = true; options.Password.RequiredLength = 8;}).AddRoles<IdentityRole>().AddEntityFrameworkStores<AppDbContext>();

// Middlewareapp.UseAuthentication();app.UseAuthorization();


Example of a protected controller:



[Authorize(Roles = "Admin")]public class AdminController : Controller{    public IActionResult Index() => View();}

// Getting the current uservar user = await _userManager.GetUserAsync(User);var roles = await _userManager.GetRolesAsync(user);


2. JWT (JSON Web Token) — Seamless Authentication for APIs and SPAs



JWT is a compact, URL-safe token that contains claims about the user. It is ideal for REST APIs, mobile applications, and Single Page Applications (React, Angular, Vue).



Installing the package:

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer


Configuration in Program.cs:



builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)    .AddJwtBearer(options =>    {        options.TokenValidationParameters = new TokenValidationParameters        {            ValidateIssuer = true,            ValidIssuer = "https://pythonlib.ru",            ValidateAudience = true,            ValidAudience = "https://api.pythonlib.ru",            ValidateLifetime = true,            IssuerSigningKey = new SymmetricSecurityKey(                Encoding.UTF8.GetBytes("SuperSecretKey123!SuperSecretKey123!")),            ClockSkew = TimeSpan.Zero        };    });


Token generation (e.g., in a login controller):



var claims = new List<Claim>{    new Claim(ClaimTypes.Name, user.UserName),    new Claim(ClaimTypes.Role, "User"),    new Claim("custom_claim", "value")};

var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SuperSecretKey123!"));var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

var token = new JwtSecurityToken( issuer: "https://pythonlib.ru", audience: "https://api.pythonlib.ru", claims: claims, expires: DateTime.Now.AddHours(2), signingCredentials: creds);

return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });


Protecting an endpoint:

[Authorize][HttpGet("profile")]public IActionResult GetProfile(){    var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;    return Ok(new { Message = "Access granted", UserId = userId });}


3. Cookie Authentication — Classic for MVC Applications



For traditional server-side applications (Razor Pages, MVC), it is convenient to use cookie authentication. The user receives an encrypted cookie that is automatically

Recommendations