CSC367 NET Centric Computing

NET Centric ComputingUnit 512 min read

State Management in Web Apps: Objects, Sessions, Cookies & Security

Unit 5 of NET Centric Computing covers how web applications maintain user-specific and global state across requests, focusing on Request, Session, Application, and Server objects in ASP.NET Core, their lifecycles, security risks (XSS/CSRF), and real-world trade-offs in stateful vs. stateless designs. Includes compariso

Core Concepts: State Management in Web Apps

Web applications are stateless by default—each HTTP request is independent. To remember user choices, logins, or app-wide settings, we use state management techniques. ASP.NET Core provides built-in objects for this:

1. Request Object (HttpRequest)

  • Purpose: Contains data from the current HTTP request (headers, query strings, form data, cookies).
  • Lifetime: Exists only for the duration of a single request.
  • Key Properties:
    HttpRequest request = HttpContext.Request;
    string ip = request.HttpContext.Connection.RemoteIpAddress.ToString();
    string path = request.Path;
    string method = request.Method; // "GET", "POST", etc.
    
  • Real-World Use:
    • eSewa: Validates user IP to prevent fraud in transactions.
    • Pathao: Uses HttpRequest to track rider locations via GPS coordinates in query strings.

2. Session Object (HttpContext.Session)

  • Purpose: Stores user-specific data across multiple requests (e.g., shopping cart, login status).
  • Lifetime: Persists until the session expires (default: 20 minutes) or the user logs out.
  • How It Works:
    • Enabled in Program.cs:
      builder.Services.AddSession(options => {
          options.IdleTimeout = TimeSpan.FromMinutes(30);
          options.Cookie.HttpOnly = true; // Prevents XSS
      });
      
    • Usage in a controller:
      public IActionResult AddToCart(int productId) {
          if (!HttpContext.Session.TryGetValue("Cart", out byte[] cartData)) {
              HttpContext.Session.SetString("Cart", "[]"); // Initialize
          }
          var cart = JsonConvert.DeserializeObject<List<int>>(HttpContext.Session.GetString("Cart"));
          cart.Add(productId);
          HttpContext.Session.SetString("Cart", JsonConvert.SerializeObject(cart));
          return RedirectToAction("Cart");
      }
      
  • Under the Hood:
    • ASP.NET Core stores session data in a cookie (encrypted) or a server-side store (Redis, SQL Server).
    • Mermaid Diagram: Session Lifecycle
      sequenceDiagram
          User->>Server: Request (e.g., "Add to Cart")
          Server->>Server: Check Session Cookie
          alt No Cookie
              Server->>User: Set Session Cookie (encrypted)
          end
          Server->>Server: Store data in session store
          Server->>User: Return response
          User->>Server: Next request (cookie included)
          Server->>Server: Retrieve session data

Worked Example: Library Management System (LMS)

  • Scenario: A student logs in and borrows books. The system must remember their borrowed books across pages.
  • Solution: Use HttpContext.Session to store:
    // After login
    HttpContext.Session.SetString("UserId", "STU123");
    HttpContext.Session.SetString("BorrowedBooks", JsonConvert.SerializeObject(new List<string> { "Book1", "Book2" }));
    
    // Later, retrieve books
    var books = JsonConvert.DeserializeObject<List<string>>(HttpContext.Session.GetString("BorrowedBooks"));
    

3. Application Object (IApplicationBuilder.ApplicationServices)

  • Purpose: Stores global data shared by all users (e.g., app configuration, cached data).
  • Lifetime: Exists for the entire application lifetime.
  • Usage:
  // In Program.cs
  var app = builder.Build();
  app.ApplicationServices.Set("AppVersion", "1.0.0");

```figure
{"type":"tree","root":{"v":"IApplicationBuilder.ApplicationServices","children":[{"v":"Dependency Injection Container","children":[{"v":"Services (e.g., ILogger, IDatabase)"},{"v":"Middleware Pipeline"}]},{"v":"Configuration","children":[{"v":"appsettings.json"},{"v":"Environment Variables"}]}]},"caption":"ApplicationServices hierarchy in ASP.NET Core"}

// In a controller var version = app.ApplicationServices.GetRequiredService<IServiceProvider>() .GetService<object>("AppVersion");

  • Real-World Use:
    • NTC (Nepal Telecom): Uses application state to cache peak-hour call rates for all users.
    • NEPSE: Stores real-time stock prices globally for all traders.

Comparison Table: Request vs. Session vs. Application

Feature Request Object Session Object Application Object
Scope Single request Single user Entire application
Lifetime Request duration Until timeout/logout App lifetime
Use Case Read-only request data User-specific data (cart) Global config/cached data
Storage Location Memory (incoming request) Cookie or server-side store Memory (static)
Security Risk None XSS if not HttpOnly None (but avoid sensitive data)

4. Server Object (ServerVariables)

  • Purpose: Provides server-level information (e.g., server name, path, headers).
  • Access:
    var server = HttpContext.Request.HttpContext.Features.Get<IServerVariablesFeature>();
    string serverName = server.ServerVariables["SERVER_NAME"];
    
  • Use Cases:
    • Load balancing (route requests based on server).
    • Logging server IP for debugging.

## In the Real World

  1. Khalti (Payment Gateway)

    • Idea Used: Session State
    • How: Stores payment session IDs in HttpContext.Session to validate transactions across multiple pages (e.g., payment confirmation). Without sessions, Khalti couldn’t link a user’s cart to their payment.
  2. Daraz (E-Commerce)

    • Idea Used: Application State + Caching
    • How: Uses IApplicationBuilder to cache product inventory counts globally. During sales events (e.g., "Daraz Days"), this reduces database load by serving pre-fetched stock levels from memory.
  3. WhatsApp Web

    • Idea Used: Stateless Design (No Server-Side Sessions)
    • How: WhatsApp Web uses short-lived tokens (stored in localStorage) instead of server-side sessions. This improves scalability but requires re-authentication if the token expires (e.g., after 24 hours).

Client-Side State Management

While ASP.NET Core handles server-side state, Single Page Applications (SPAs) like Angular/React manage state on the client. Compare:

Feature Angular (RxJS + Services) React (Redux/Context API) ASP.NET Core (Server-Side)
State Storage Client memory Client memory Server (Session/DB)
Scalability High (no server load) High Low (server-side storage)
Security Vulnerable to XSS Vulnerable to XSS Secure (if HttpOnly)
Real-Time Sync Requires WebSockets Requires WebSockets Built-in (SignalR)
Example Use Dashboards (eSewa admin) Social media feeds (Facebook) E-commerce carts (Daraz)

Worked Example: Angular + ASP.NET Core Integration

  • Scenario: A library app built with Angular for the UI and ASP.NET Core for the backend.
  • State Flow:
    1. User logs in via Angular’s AuthService (stores token in localStorage).
    2. Angular sends the token in every API call to ASP.NET Core’s [Authorize] endpoints.
    3. ASP.NET Core validates the token and retrieves user data from HttpContext.Session.
sequenceDiagram
    User->>Angular: Login (username/password)
    Angular->>ASP.NET Core: POST /api/auth/login
    ASP.NET Core->>User: Return JWT token
    Angular->>localStorage: Store token
    Angular->>ASP.NET Core: GET /api/books (with token)
    ASP.NET Core->>Session: Validate token
    ASP.NET Core->>User: Return book list

Security Threats in State Management

011.2522.533.7545XSS45CSRF30Session Hijacking20Token Theft5
Relative frequency of state management attacks (based on OWASP data)

1. Cross-Site Scripting (XSS)

  • Attack: Malicious script injected into session data (e.g., via a form).
  • Prevention:
    • Use [ValidateAntiForgeryToken] in Razor Pages.
    • Sanitize inputs with HtmlEncoder.
    • Set HttpOnly and Secure flags on session cookies:
      options.Cookie.HttpOnly = true;
      options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
      

2. Cross-Site Request Forgery (CSRF)

  • Attack: Tricks users into submitting malicious requests (e.g., changing password).
  • Prevention:
    • Use ASP.NET Core’s Anti-Forgery Tokens:
      @Html.AntiForgeryToken() <!-- In Razor Views -->
      
    • Validate tokens in controllers:
      [ValidateAntiForgeryToken]
      public IActionResult ChangePassword(PasswordModel model) { ... }
      

3. Session Hijacking

  • Attack: Stealing session cookies (e.g., via MITM attacks).
  • Prevention:
    • Use HTTPS (enforced via app.UseHttpsRedirection()).
    • Regenerate session IDs after login:
      HttpContext.Session.SetCookie(new SessionCookieOptions {
          IsEssential = true,
          Regenerate = true
      });
      

Hosting Models for State Management

ASP.NET Core supports different ways to store session data:

Model Description Pros Cons
In-Memory Stores sessions in server RAM. Fast Not scalable (single server)
Cookie-Based Encrypted session data in client cookies. Works without server store Limited size (~4KB)
Distributed Cache (Redis) Sessions stored in a Redis server. Scalable, high performance Requires Redis setup
SQL Server Sessions stored in a database table. Persistent, auditable Slower than Redis

Exam Tip

What Examiners Look For

  1. Definitions:

    • Clearly distinguish between Request, Session, and Application objects (scope, lifetime, use cases).
    • Example: "The Request object is ephemeral, while the Session object persists until timeout."
  2. Code Snippets:

    • Show how to enable sessions in Program.cs and how to use them in a controller.
    • Example: Missing builder.Services.AddSession() will cost marks!
  3. Security:

    • Always mention XSS/CSRF protections (e.g., HttpOnly, Secure, AntiForgeryToken).
    • Example: "To prevent XSS, set options.Cookie.HttpOnly = true."
  4. Real-World Applications:

    • Link concepts to eSewa (sessions), Daraz (application state), or WhatsApp (stateless design).
    • Example: "Khalti uses session state to validate payment sessions across multiple pages."
  5. Comparisons:

    • Compare Angular/React (client-side state) vs. ASP.NET Core (server-side state) in a table.
    • Example: "React’s Redux is client-side, while ASP.NET Core’s HttpContext.Session is server-side."
  6. Diagrams:

    • Draw sequence diagrams for state flow (e.g., login → session creation → data retrieval).
    • Example: A 3-step sequence showing Angular → ASP.NET Core → Session Store.

Common Pitfalls

  • Forgetting to enable sessions: Always include app.UseSession() in the middleware pipeline.
  • Storing sensitive data in cookies: Use HttpContext.Session for sensitive data (encrypted by default).
  • Ignoring security flags: Never skip HttpOnly or Secure for session cookies.
  • Confusing Application vs. Session: Application state is global; session state is user-specific.

Final Note: State management is the bridge between stateless HTTP and user experience. Master the trade-offs (scalability vs. security, client vs. server state) and you’ll ace both theoretical and practical questions. For the exam, prioritize diagrams, code snippets, and real-world examples—they fetch the highest marks!

Based on the TU BSc CSIT syllabus for NET Centric Computing (CSC367), unit 5.

Discussion

Loading…