Authentication and Authorization
Introduction
This tutorial will guide you through the process of setting up authentication and authorization in an ASP.NET Core application. We will cover basic authentication using cookies and roles-based authorization.
Setting Up the Development Environment
Before you start, ensure you have the following installed:
- Visual Studio 2019 or later
- .NET Core SDK
Example: Installing .NET Core SDK
https://dotnet.microsoft.com/download/dotnet-core
Creating a New ASP.NET Core Project
Open Visual Studio and create a new project:
- Select "Create a new project".
- Choose "ASP.NET Core Web Application" and click "Next".
- Name your project and select the location to save it. Click "Create".
- In the "Create a new ASP.NET Core Web Application" dialog, select "Web Application (Model-View-Controller)" and click "Create".
Adding Authentication
To add authentication to your application, you need to configure services and middleware in the Startup.cs
file:
Example: Configuring Authentication in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
// Add authentication
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Account/Login";
options.AccessDeniedPath = "/Account/AccessDenied";
});
// Add authorization
services.AddAuthorization(options =>
{
options.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
Creating the Account Controller
Create a new controller named AccountController
to handle user authentication actions like login and logout:
Example: AccountController
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using System.Threading.Tasks;
public class AccountController : Controller
{
public IActionResult Login()
{
return View();
}
[HttpPost]
public async Task Login(string username, string password)
{
if (username == "admin" && password == "password")
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, username),
new Claim(ClaimTypes.Role, "Admin")
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));
return RedirectToAction("Index", "Home");
}
return View();
}
public async Task Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return RedirectToAction("Login");
}
public IActionResult AccessDenied()
{
return View();
}
}
Creating the Login View
Add a new view named Login.cshtml
in the Views/Account
folder to allow users to input their login credentials:
Example: Login.cshtml
<h2>Login</h2>
<form asp-action="Login" method="post">
<div>
<label>Username</label>
<input type="text" name="username" />
</div>
<div>
<label>Password</label>
<input type="password" name="password" />
</div>
<button type="submit">Login</button>
</form>
Protecting Routes
To protect certain routes, you can use the [Authorize]
attribute in your controllers. For example, to restrict access to the AdminController to only users with the Admin role:
Example: AdminController
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
[Authorize(Roles = "Admin")]
public class AdminController : Controller
{
public IActionResult Index()
{
return View();
}
}
Running the Application
Run the application by pressing F5
or clicking the "Run" button in Visual Studio. Navigate to https://localhost:5001/
and try to access the protected routes. If not logged in, you will be redirected to the login page.
Conclusion
Congratulations! You have implemented authentication and authorization in an ASP.NET Core application. This tutorial covered the basics of setting up a new project, configuring authentication and authorization, creating login and logout actions, and protecting routes. From here, you can extend the application with more features and integrate it with a backend service for user management.