Authentication and Authorization in C#
Introduction
In this tutorial, we will explore the concepts of Authentication and Authorization in the context of C# programming. Authentication is the process of verifying the identity of a user, while Authorization determines what an authenticated user is allowed to do. Both concepts are essential for securing applications.
Authentication
Authentication is the process of verifying who someone is. This is typically done using a username and password. In C# applications, especially web applications, authentication can be achieved using various frameworks and protocols such as ASP.NET Identity, OAuth, and OpenID Connect.
Example: Basic Authentication with ASP.NET Core
First, create a new ASP.NET Core project:
dotnet new webapp -n AuthExample
Next, set up ASP.NET Core Identity in the Startup.cs
file:
public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddDbContext(options => options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection"))); services.AddDefaultIdentity (options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores (); services.AddRazorPages(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } }
Run the application and navigate to the registration page to create a new user account. ASP.NET Core Identity will handle the authentication process for you.
Authorization
Authorization is the process of determining what an authenticated user is allowed to do. It involves checking the user's permissions against a set of rules defined within the application. In ASP.NET Core, authorization can be managed using policies and roles.
Example: Role-Based Authorization
First, ensure roles are added when users are created or updated:
public async TaskOnPostAsync() { var user = new IdentityUser { UserName = Input.Email, Email = Input.Email }; var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { await _userManager.AddToRoleAsync(user, "Administrator"); // more code... } }
Next, configure role-based authorization in the Startup.cs
file:
public void ConfigureServices(IServiceCollection services) { services.AddAuthorization(options => { options.AddPolicy("AdminOnly", policy => policy.RequireRole("Administrator")); }); services.AddControllersWithViews(); }
Finally, apply the policy to a controller or action method:
[Authorize(Policy = "AdminOnly")] public class AdminController : Controller { public IActionResult Index() { return View(); } }
Conclusion
In this tutorial, we covered the basics of Authentication and Authorization in C#. We demonstrated how to set up basic authentication using ASP.NET Core Identity and how to implement role-based authorization. Securing your application is crucial, and understanding these concepts is a fundamental step in that direction.