Search code examples
asp.net-coresessionasp.net-core-webapi

ASP.NET Core WebAPI Session with redirect


I'm trying to store a session in my WebAPI's first method, and get it from a second method. I'm using HttpContext.Session.SetString and I've included the required app.useSession and services.AddDistributedMemoryCache(), services.AddSession() methods in my statup file.

The problem is, my first method has a return type of "RedirectResult" and at the and of it is doing a new Redirect("http:// ...")

And then when I try to run the second method, the session is null. I assume because the session cookie headers sent to the browser in the first method are being overridden by the redirect.

So how can I do this? I'm trying to store a code_verifier string (for OAuth PKCE implementation) and then redirect to an OAuth code request endpoint

It seems my initial suspicion was incorrect; this has nothing to do with the redirect.

When the OAuth server redirects back to my second WebAPI's method, it does this via POST. And for some reason the cookies (including the AspNetCore.Session cookie) are not being sent unlike when I try to make the request via a normal GET in the browser...

I do see the SameSite for the AspNetCore.Session cookie is set to LAX. So how can I do this?


Solution

  • A "LAX" cookie doesn't allow it to be carried over when the request comes via POST from a 3rd party.

    The problem was resolved by setting the SameSite property for the .NET core session cookie to "None". This also requires that the Secure flag be set to "true" and the WebAPI runs over HTTPS.

    The previous session cookie had to be removed manually from the browser for this to take affect.

    services.AddSession(options =>
    {
        options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.None;
        options.Cookie.SecurePolicy = Microsoft.AspNetCore.Http.CookieSecurePolicy.Always;                
    });
    
    services.AddSession();