Authentication and authorization are critical components of web application security. In ASP.NET Core, these features can be implemented using built-in middleware and services. This guide will walk you through the steps to set up authentication and authorization in an ASP.NET Core application.

1. Setting Up Authentication

To implement authentication, you need to configure the authentication services in the Startup.cs file. ASP.NET Core supports various authentication schemes, including cookie authentication and JWT bearer authentication.

Sample Code for Cookie Authentication

        
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Account/Login"; // Redirect to login page
options.LogoutPath = "/Account/Logout"; // Redirect to logout page
});

services.AddControllersWithViews();
}

2. Creating the Login and Logout Actions

Next, you need to create actions in your controller to handle user login and logout. The login action will validate user credentials and sign in the user.

Sample Code for Login Action

        
public class AccountController : Controller
{
[HttpGet]
public IActionResult Login()
{
return View();
}

[HttpPost]
public async Task<IActionResult> Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
// Validate user credentials (this is just a placeholder)
if (model.Username == "admin" && model.Password == "password")
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, model.Username),
new Claim(ClaimTypes.Role, "Admin")
};

var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties
{
IsPersistent = model.RememberMe
};

await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);
return RedirectToAction("Index", "Home");
}
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
}
return View(model);
}

public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return RedirectToAction("Index", "Home");
}
}

3. Implementing Authorization

Authorization determines whether a user has permission to access certain resources. In ASP.NET Core, you can use attributes to enforce authorization at the controller or action level.

Sample Code for Role-based Authorization

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

4. Using Policies for Authorization

In addition to role-based authorization, you can define custom policies for more granular control over access.

Sample Code for Policy-based Authorization

        
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthorization(options =>
{
options.AddPolicy("RequireAdministratorRole", policy => policy.RequireRole("Admin"));
});
}

[Authorize(Policy = "RequireAdministratorRole")]
public class AdminController : Controller
{
public IActionResult Dashboard()
{
return View();
}
}

5. Protecting Routes

To protect specific routes, you can use the [Authorize] attribute on controllers or actions. This ensures that only authenticated users can access those routes.

Sample Code for Protecting a Route

        
[Authorize]
public class UserController : Controller
{
public IActionResult Profile()
{
return View();
}
}

Conclusion

Implementing authentication and authorization in ASP.NET Core is straightforward and flexible. By configuring authentication services, creating login/logout actions, and applying authorization attributes, developers can secure their applications effectively. Whether using role-based or policy-based authorization, ASP.NET Core provides the tools necessary to protect resources and ensure that only authorized users can access them.