0% found this document useful (0 votes)
21 views28 pages

C# Concepts 6

Uploaded by

musabinshabeer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views28 pages

C# Concepts 6

Uploaded by

musabinshabeer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 28

C# Concepts

Cookies and Sessions on the Backend


C#: Cookies and Sessions on the
Backend

• Cookies and sessions are mechanisms to store user data and maintain
state between HTTP requests in web applications. In ASP.NET Core,
managing cookies and sessions involves configuring middleware and
using appropriate APIs.
C#: Cookies

• Definition: Cookies are small pieces of data stored on the client's


browser and sent with every HTTP request to the server. They are
commonly used for authentication tokens, user preferences, and
tracking user activity.
Types of Cookies:
• Session Cookies: Temporary cookies that are deleted when the
browser closes.

• Persistent Cookies: Remain on the client's device for a specified


period.

• Secure Cookies: Only sent over HTTPS.

• HttpOnly Cookies: Not accessible via JavaScript, mitigating XSS


attacks.
Setting a Cookie: Example – Setting a Cookie in
ASP.NET Core

using Microsoft.AspNetCore.Mvc;

public class CookieController : Controller


{
[HttpGet]
[Route("SetCookie")]
public IActionResult SetCookie()
{
Setting a Cookie: Example – Setting a Cookie in
ASP.NET Core
CookieOptions options = new CookieOptions
{
Expires = DateTime.Now.AddDays(1),
HttpOnly = true,
Secure = true, // Ensure cookie is only sent over
HTTPS
SameSite = SameSiteMode.Strict
};
Response.Cookies.Append("UserName", "JohnDoe",
options);
return Ok("Cookie has been set.");
}
Reading a Cookie: Example – Reading a Cookie in
ASP.NET Core

using Microsoft.AspNetCore.Mvc;

public class CookieController : Controller


{
[HttpGet]
[Route("GetCookie")]
public IActionResult GetCookie()
{
Reading a Cookie: Example – Reading a Cookie in
ASP.NET Core

if (Request.Cookies.TryGetValue("UserName", out
string userName))
{
return Ok($"UserName: {userName}");
}
return NotFound("Cookie not found.");
}
}
Deleting a Cookie: Example – Deleting a Cookie in
ASP.NET Core

using Microsoft.AspNetCore.Mvc;

public class CookieController : Controller


{
[HttpGet]
[Route("DeleteCookie")]
public IActionResult DeleteCookie()
{
Deleting a Cookie: Example –
Deleting a Cookie in ASP.NET Core
if (Request.Cookies.ContainsKey("UserName"))
{
Response.Cookies.Delete("UserName");
return Ok("Cookie deleted.");
}
return NotFound("Cookie not found.");
}
}
Cookies - Security Considerations
• HttpOnly: Prevents JavaScript access, mitigating XSS attacks.

• Secure: Ensures cookies are only transmitted over HTTPS.

• SameSite: Controls whether cookies are sent with cross-site


requests, helping prevent CSRF attacks.
C#: Sessions

• Definition: Sessions store user data on the server side and are
identified by a unique session ID, typically stored in a cookie on the
client's browser. Sessions are used to maintain state across multiple
HTTP requests.
Sessions - Characteristics:
• Server-Side Storage: Data is stored on the server, reducing
exposure to client-side manipulation.

• Scoped to User: Each user has a unique session.

• Expiration: Sessions can expire after a period of inactivity.


Configuring Sessions in ASP.NET
Core - Add Session Services
In Program.cs or Startup.cs:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.


builder.Services.AddControllers();

// Add distributed memory cache (required for sessions)


builder.Services.AddDistributedMemoryCache();
Configuring Sessions in ASP.NET
Core - Add Session Services
// Configure session options
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30); // Session timeout
options.Cookie.HttpOnly = true; // Prevent JavaScript access
options.Cookie.IsEssential = true; // Essential for the application
options.Cookie.SecurePolicy = CookieSecurePolicy.Always; // Always
secure
options.Cookie.SameSite = SameSiteMode.Strict;
});
Configuring Sessions in ASP.NET
Core - Add Session Services
// Use session middleware
app.UseSession();

app.UseRouting();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
Using Sessions in Controllers -
Example: Setting and Getting
Session Data
using Microsoft.AspNetCore.Mvc;

public class SessionController : Controller


{
[HttpGet]
[Route("SetSession")]
public IActionResult SetSession()
{
HttpContext.Session.SetString("UserName", "JohnDoe");
HttpContext.Session.SetInt32("UserId", 123);
return Ok("Session data has been set.");
Using Sessions in Controllers -
Example: Setting and Getting
Session
[HttpGet]
Data
[Route("GetSession")]
public IActionResult GetSession()
{
var userName = HttpContext.Session.GetString("UserName");
var userId = HttpContext.Session.GetInt32("UserId");

if (userName != null && userId.HasValue)


{
return Ok($"UserName: {userName}, UserId: {userId.Value}");
}
return NotFound("Session data not found.");
Using Sessions in Controllers -
Example: Setting and Getting
Session Data
[HttpGet]
[Route("ClearSession")]
public IActionResult ClearSession()
{
HttpContext.Session.Clear();
return Ok("Session data cleared.");
}
}
C#: Storing Complex Objects in
Sessions

• Since sessions can only store byte arrays, strings, or integers directly,
to store complex objects, you need to serialize and deserialize them,
typically using JSON.
Example - Storing a Complex Object
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

public static class SessionExtensions


{
public static void SetObjectAsJson(this ISession session,
string key, object value)
{
session.SetString(key,
JsonConvert.SerializeObject(value));
Example - Storing a Complex Object
public static T GetObjectFromJson<T>(this ISession session,
string key)
{
var value = session.GetString(key);
return value == null ? default(T) :
JsonConvert.DeserializeObject<T>(value);
}
}
Example - Usage in Controller
using Microsoft.AspNetCore.Mvc;

public class SessionController : Controller


{
[HttpGet]
[Route("SetUserSession")]
public IActionResult SetUserSession()
{
Example - Usage in Controller
var user = new User
{
Id = 1,
Name = "John Doe",
Email = "[email protected]"
};
HttpContext.Session.SetObjectAsJson("User", user);
return Ok("User session has been set.");
}
Example - Usage in Controller
[HttpGet]
[Route("GetUserSession")]
public IActionResult GetUserSession()
{
var user = HttpContext.Session.GetObjectFromJson<User>("User");
if (user != null)
{
return Ok($"User: {user.Name}, Email: {user.Email}");
}
return NotFound("User session not found.");
}
}
Sessions - Security Considerations
• Session Hijacking: Ensure session IDs are secure and
transmitted over HTTPS.

• Session Fixation: Regenerate session IDs upon


authentication.

• Data Sensitivity: Avoid storing sensitive data directly in


sessions; use secure storage mechanisms.
Differences Between Cookies and
Sessions
Aspect Cookies Sessions

Storage Location Client-side (browser) Server-side


Data Size Limit Typically limited to ~4KB per cookie Limited by server memory/resources
Lifetime Configurable (persistent or session) Configurable (based on timeout settings)
Security Vulnerable to XSS (unless HttpOnly) More secure as data is on the server
Performance Sent with every HTTP request, increasing
Minimal impact on request payload
payload size
Use Cases Storing user preferences, authentication
Storing user-specific data across requests
tokens
Sessions - Best Practices
• Use Cookies for lightweight, non-sensitive data or
authentication tokens (with proper security flags).

• Use Sessions for storing sensitive or larger amounts of


data that shouldn't be exposed to the client.

You might also like