app.UseCookieAuthentication - SessionStore

amal James 0 Reputation points
2025-02-21T16:16:47.76+00:00

Hi Team,

I have a scenario where in asp.net MVC application the session Key (GUID every time user logs in) is stored to a SQL database Table.

The below methods are used.
I need suggestions for two things

1.The underlying database Can have any number of fields other than Key, Ticketstring ,TicketExpiry.

is it an issue if I add more fields? As the table is handled by asp.net framework?

2.As part of session killing from external application I need to send this key to an API, but I need this key to be fetched from other places where the API calls are happening .Please suggest an approach to do it, I tried to add this key to claims and to retrieve it but the key is missing in claims when I try to fetch it

public async Task<string> StoreAsync(AuthenticationTicket ticket)
{
   string Key = Guid.NewGuid().ToString();

//inserting key,TicketString,TicketExpiry to database

   return Task.FromResult(key);

}
public Task RenewAsync(string key, AuthenticationTicket ticket) {

//inserting key,TicketString,TicketExpiry to database
}
 app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
/*
 OtherProperties
*/
  SessionStore = new SqlAuthenticationSessionStore(ticketFormat,db_connectionString)
}
Developer technologies | ASP.NET | ASP.NET API
{count} votes

3 answers

Sort by: Most helpful
  1. Danny Nguyen (WICLOUD CORPORATION) 5,375 Reputation points Microsoft External Staff Moderator
    2025-07-23T10:20:35.5333333+00:00

    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.


    1 person found this answer helpful.

  2. Bruce (SqlWork.com) 82,146 Reputation points Volunteer Moderator
    2025-02-22T16:41:10.5933333+00:00

    Storing the key as a claim is the correct approach. There should be no issue with adding custom claims with cookie authentication.

    0 comments No comments

  3. SurferOnWww 5,026 Reputation points
    2025-02-23T00:53:42.9+00:00

    its an MVC app

    I recommend that you use the ASP.NET Identity. The following articles will be helpful to add the key as a claim to the ClamsIdentity:

    If you enable the Role in the ASP.NET Identity, please use the UserClaimsPrincipalFactory<TUser,TRole> instead of UserClaimsPrincipalFactory<TUser>.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.