Basic Authentication

Understanding Basic Authentication in .NET

Authentication is a fundamental aspect of web application security. It ensures that users are who they claim to be, allowing access to authorized resources while safeguarding sensitive data. In this chapter, we will explore the basics of authentication, focusing on cookie authentication, and how it is implemented in .NET MVC applications.

What is Authentication?

Authentication is the process of verifying the identity of a user or system. In a web application, this typically involves checking credentials such as a username and password. Once verified, the application can grant the user access to restricted areas or functionality.

Authentication works hand-in-hand with authorization, which determines what a user is allowed to do based on their identity. For example, after logging in, a user might have access to their profile page but not to the admin dashboard.

Cookie authentication is one of the most common methods used in web applications. It works by storing a small piece of data, called a cookie, in the user’s browser. This cookie serves as a token that identifies the user for subsequent requests.

The process can be broken down into the following steps:

  1. User Login: The user submits their credentials (e.g., username and password) through a login form.
  2. Server Validation: The server verifies the credentials by checking them against the stored user data (e.g., in a database).
  3. Token Creation: Upon successful validation, the server generates an authentication cookie. This cookie may include user-specific data such as a unique user ID or a session identifier.
  4. Cookie Storage: The authentication cookie is sent to the user’s browser and stored.
  5. Subsequent Requests: For every subsequent request, the browser automatically includes the cookie. The server uses this cookie to identify the user and verify their session.
  6. Logout: When the user logs out, the authentication cookie is invalidated or removed, ending the session.

Example Flow

In a .NET MVC application, cookie authentication is implemented using the built-in Authentication Middleware. Let’s break down how to set it up in a minimalistic manner.

Step 1: Configure Authentication in Program.cs

In your Program.cs file, configure cookie authentication using the AddAuthentication and AddCookie methods.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication("CookieAuth")
    .AddCookie("CookieAuth", options =>
    {
        options.LoginPath = "/Account/Login";
        options.Cookie.Name = "AuthCookie";
    });

builder.Services.AddControllersWithViews();

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

Step 2: Create the Login Action

In your AccountController, create a Login action to handle user login. This action validates the user credentials and issues an authentication cookie.

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

    [HttpPost]
    public async Task<IActionResult> Login(string username, string password)
    {
        if (username == "admin" && password == "password")
        {
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, username)
            };

            var identity = new ClaimsIdentity(claims, "CookieAuth");
            var principal = new ClaimsPrincipal(identity);

            await HttpContext.SignInAsync("CookieAuth", principal);
            return RedirectToAction("Index", "Home");
        }

        ViewData["Error"] = "Invalid username or password.";
        return View();
    }

    public async Task<IActionResult> Logout()
    {
        await HttpContext.SignOutAsync("CookieAuth");
        return RedirectToAction("Login");
    }
}

Step 3: Create the Login View

Add a Login.cshtml file in the Views/Account folder to create the login form.

@{
    ViewData["Title"] = "Login";
}

<h2>Login</h2>

<form method="post">
    <div>
        <label>Username:</label>
        <input type="text" name="username" required />
    </div>
    <div>
        <label>Password:</label>
        <input type="password" name="password" required />
    </div>
    <button type="submit">Login</button>
</form>

@if (ViewData["Error"] != null)
{
    <p style="color:red">@ViewData["Error"]</p>
}

Step 4: Protect Actions with [Authorize]

Use the [Authorize] attribute to restrict access to actions or controllers. For example:

[Authorize]
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

Security Considerations

The above implementation is minimal and may lack certain security features. In production:

  1. Use HTTPS: Ensure cookies are transmitted securely.
  2. Secure Cookies: Set options.Cookie.SecurePolicy = CookieSecurePolicy.Always.
  3. HttpOnly Cookies: Enable the HttpOnly flag to prevent access to cookies via JavaScript.
  4. Validate Inputs: Add proper input validation and hashing for credentials.

Conclusion

Cookie authentication is a straightforward and effective way to manage user sessions in an MVC application. By integrating it into your .NET MVC project, you can secure routes and manage user identity seamlessly. While the examples here provide a minimal implementation, ensure that you follow security best practices for production environments.