Skip to main content

Overview

SupermarketWEB implements a cookie-based authentication system using ASP.NET Core Identity. The system provides secure login, registration, and logout functionality to protect administrative features.

Authentication Configuration

The authentication system is configured in Program.cs:19-23 using cookie-based authentication:
builder.Services.AddAuthentication().AddCookie("MyCookieAuth", option =>
{
    option.Cookie.Name = "MyCookieAuth";
    option.LoginPath = "/Account/Login";
});
The authentication cookie is named “MyCookieAuth” and users are automatically redirected to /Account/Login when attempting to access protected resources.

User Model

The User model (Models/User.cs:5-14) defines the structure for user accounts:
public class User
{
    public int Id { get; set; }
    
    [Required]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }
    
    [Required]
    [DataType(DataType.Password)]
    public string Password { get; set; }
}

Properties

PropertyTypeValidationDescription
Idint-Unique identifier
EmailstringRequired, Email formatUser’s email address
PasswordstringRequired, Password data typeUser’s password

Authentication Flow

1

User Registration

New users register through the /Account/Register page, providing email and password credentials.
2

Credential Validation

The system validates the user input and stores the new user in the database.
3

Login Process

Users authenticate by providing their email and password on the /Account/Login page.
4

Session Creation

Upon successful authentication, a claims-based identity is created and stored in a cookie.

Login Implementation

The login process (Pages/Account/Login.cshtml.cs:28-50) validates credentials and creates authentication cookies:
public async Task<IActionResult> OnPostAsync()
{
    if (!ModelState.IsValid) return Page();

    var existUser = await _context.Users
        .FirstOrDefaultAsync(u => u.Email == User.Email && u.Password == User.Password);

    if (existUser != null)
    {
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, "admin"),
            new Claim(ClaimTypes.Email, User.Email),
        };
        var identity = new ClaimsIdentity(claims, "MyCookieAuth");
        ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(identity);
        await HttpContext.SignInAsync("MyCookieAuth", claimsPrincipal);
        return RedirectToPage("/Index");
    }
    return Page();
}

Claims-Based Identity

The system creates two claims for authenticated users:
  • Name Claim: Set to “admin” for all authenticated users
  • Email Claim: Stores the user’s email address

Registration Implementation

User registration (Pages/Account/Register.cshtml.cs:25-36) adds new users to the database:
public async Task<IActionResult> OnPostAsync()
{
    if (!ModelState.IsValid || _context.Users == null || User == null)
    {
        return Page();
    }

    _context.Users.Add(User);
    await _context.SaveChangesAsync();

    return RedirectToPage("Login");
}
The current implementation stores passwords in plain text. In a production environment, passwords should be hashed using a secure algorithm like bcrypt or PBKDF2.

Logout Implementation

The logout process (Pages/Account/Logout.cshtml.cs:9-13) clears the authentication cookie:
public async Task<IActionResult> OnPostAsync() 
{
    await HttpContext.SignOutAsync("MyCookieAuth");
    return RedirectToPage("/Index");
}

Protected Resources

Pages requiring authentication use the [Authorize] attribute:
[Authorize]
public class IndexModel : PageModel
{
    // Protected page implementation
}
All CRUD operations for Products, Categories, Customers, and PayModes are protected with the [Authorize] attribute.

Security Features

Cookie-Based Sessions

Secure session management using encrypted cookies

Automatic Redirects

Unauthenticated users are redirected to the login page

Claims-Based Identity

User information stored in secure claims

Authorization Attributes

Simple [Authorize] attribute protects pages

Database Storage

User data is stored in the Users table via the SupermarketContext (Data/SupermarketContext.cs:17):
public DbSet<User> Users { get; set; }

Best Practices

For Production Deployments:
  1. Implement password hashing (e.g., Identity’s PasswordHasher)
  2. Add password complexity requirements
  3. Implement account lockout after failed attempts
  4. Use HTTPS for all authentication endpoints
  5. Consider implementing two-factor authentication
  6. Add email verification for new registrations

Build docs developers (and LLMs) love