Authorization and Authentication in C# (.NET)
In modern web development on the .NET platform, the topics of authentication (verifying user identity) and authorization (checking access rights) are fundamental. The libraries and built-in mechanisms of ASP.NET Core provide a powerful and flexible toolkit for implementing these tasks. In this article, we will thoroughly examine the main approaches, including the use of JWT (JSON Web Tokens), ASP.NET Core Identity, and built-in middleware components.
Core Concepts
- Authentication — the process of verifying who the user is (e.g., login + password).
- Authorization — the process of determining what the user can do (roles, policies, claims).
- Claims-based identity — an approach where user information is stored as a set of claims.
ASP.NET Core Identity
ASP.NET Core Identity is a full-featured user management system that includes registration, login, password reset, two-factor authentication, and role management. It uses Entity Framework Core to store data in the database.
To add Identity to a project, simply call AddDefaultIdentity and configure the connection string. Example of basic setup in Program.cs:
using Microsoft.AspNetCore.Identity;using Microsoft.EntityFrameworkCore;using YourApp.Data;
var builder = WebApplication.CreateBuilder(args);
// Add DB contextbuilder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
// Add Identitybuilder.Services.AddDefaultIdentity<IdentityUser>(options => { options.SignIn.RequireConfirmedAccount = false; options.Password.RequireDigit = true; options.Password.RequiredLength = 6;}).AddRoles<IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.UseAuthentication();app.UseAuthorization();
app.MapRazorPages();app.Run();After this, standard registration and login pages become available, as well as methods for checking roles:
[Authorize(Roles = "Admin")]public IActionResult AdminPanel(){ return View();}JWT Authentication (JSON Web Tokens)
JWT is a compact and self-contained way to transmit information between parties as a JSON object. In .NET, JWT is often used for building REST APIs and SPA applications. The main library is Microsoft.AspNetCore.Authentication.JwtBearer.
JWT configuration in Program.cs:
using Microsoft.AspNetCore.Authentication.JwtBearer;using Microsoft.IdentityModel.Tokens;using System.Text;
var builder = WebApplication.CreateBuilder(args);
var key = Encoding.ASCII.GetBytes("YourSuperSecretKeyThatIsAtLeast32CharactersLong!");
builder.Services.AddAuthentication(options =>{ options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;}).AddJwtBearer(options =>{ options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = "yourdomain.com", ValidAudience = "yourdomain.com", IssuerSigningKey = new SymmetricSecurityKey(key) };});
builder.Services.AddAuthorization();builder.Services.AddControllers();
var app = builder.Build();app.UseAuthentication();app.UseAuthorization();app.MapControllers();app.Run();Example