Hi James,
To address your questions:
1. Can I add more fields to the session table?
Yes, you can add more fields to the table. The ASP.NET framework will only interact with the fields it knows about (typically Key, TicketString, TicketExpiry). Any additional fields you add will be ignored by the framework unless you explicitly read/write them in your custom session store implementation.
2. How can I fetch the session key (GUID) later in other parts of the app (e.g., API layer)?
Your issue is that the session key (GUID) stored in the database isn’t reliably available in claims when accessed from other parts of the application or external API calls. This suggests a problem with how the key is being stored or propagated.
Recommended Approaches:
Approach A: Store the key in the Authentication Cookie's Properties
When you generate the ticket, add the session key to AuthenticationProperties:
var properties = ticket.Properties;
properties.Dictionary["SessionKey"] = key; // or any custom key
Later, in any part of the app (Controller, Middleware), you can retrieve it like this:
var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
var sessionKey = result?.Properties?.Items["SessionKey"];
Approach B: Store Session Key in HttpContext.Items
If the key is only needed per-request, you can store it like this in middleware:
app.Use(async (context, next) =>
{
var authResult = await context.AuthenticateAsync();
var sessionKey = authResult?.Properties?.Items["SessionKey"];
context.Items["SessionKey"] = sessionKey;
await next();
});
Then access it anywhere in your request pipeline:
var key = HttpContext.Items["SessionKey"]?.ToString();
Approach C: Store the SessionKey in a Claim (with care)
You can technically store it in claims, but keep in mind:
- The claims get serialized into the cookie, and long or dynamic values can make the cookie size large.
- Also, modifying claims after user signs in requires creating a new ticket and re-signing in.
If you still want to try:
var identity = (ClaimsIdentity)ticket.Identity;
identity.AddClaim(new Claim("SessionKey", key));
Then access:
var sessionKey = User.Claims.FirstOrDefault(c => c.Type == "SessionKey")?.Value;
Ensure you resign the user in after adding the claim.