Skip to content

AddSession Sets wrong Cookie Path #48165

@Coder3333

Description

@Coder3333

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

SessionServiceCollectionExtensions.AddSession creates a cookie with the Path of "/", ignoring the path base of the web application. This is further complicated in that AddSession does not provide a way to access the HttpContext, so my code cannot easily set the cookie path to the desired value.

Documents cookie behavior of AddSession:
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-7.0#session-options

Documents the problem:
https://stackoverflow.com/q/54362266/4194514

Expected Behavior

The cookie created by SessionServiceCollectionExtensions.AddSession should use the path base of the web application, similarly to how antiforgery token does.

Steps To Reproduce

Give your web application a path base and use SessionServiceCollectionExtensions.AddSession to add session to the website, but do not specify a path of the session cookie. You will see in code that the path of the cookie is set by the framework to "/", which I believe comes from SessionDefaults.CookiePath.

Exceptions (if any)

No response

.NET Version

No response

Anything else?

I see 3 different ways to fix this issue.

  1. Automatically set the cookie Path to the application's PathBase, instead of SessionDefaults.CookiePath.
  2. Change the value of SessionDefaults.CookiePath from "/" to the application's path base.
  3. Add an additional signature to SessionServiceCollectionExtensions.AddSession that accepts the http context, so my custom code can determine the PathBase and set it as the cookie path.

Activity

added
breaking-changeThis issue / pr will introduce a breaking change, when resolved / merged.
on May 10, 2023
Tratcher

Tratcher commented on May 10, 2023

@Tratcher
Member

Here is what Antiforgery does:

public void SaveCookieToken(HttpContext httpContext, string token)
{
Debug.Assert(httpContext != null);
Debug.Assert(token != null);
var options = _options.Cookie.Build(httpContext);
if (_options.Cookie.Path != null)
{
options.Path = _options.Cookie.Path;
}
else
{
var pathBase = httpContext.Request.PathBase.ToString();
if (!string.IsNullOrEmpty(pathBase))
{
options.Path = pathBase;
}
}
httpContext.Response.Cookies.Append(_options.Cookie.Name!, token, options);

Changing the default for Session would be breaking. Note we also use / for auth. I'm not sure why Antiforgery does something different.

edit nevermind, auth also uses path base by default.

public override CookieOptions Build(HttpContext context, DateTimeOffset expiresFrom)
{
// check if the user has overridden the default value of path. If so, use that instead of our default value.
var path = Path;
if (path == null)
{
var originalPathBase = context.Features.Get<IAuthenticationFeature>()?.OriginalPathBase ?? context.Request.PathBase;
path = originalPathBase + AdditionalPath;
}
var options = base.Build(context, expiresFrom);
options.Path = !string.IsNullOrEmpty(path)
? path
: "/";
return options;

Coder3333

Coder3333 commented on May 11, 2023

@Coder3333
Author

@Tratcher , I haven't tracked down the Microsoft source code, yet, but in my application AddAuthentication and AddAntiforgery are creating their cookies with the proper path base, even though I am not doing anything to control that value. So far, AddSession is the only one of these that is creating the cookie at "/".

added
area-middlewareIncludes: URL rewrite, redirect, response cache/compression, session, and other general middlewares
and removed on Jun 2, 2023
removed
pending-ci-rerunWhen assigned to a PR indicates that the CI checks should be rerun
on Feb 6, 2024
ahaeber

ahaeber commented on Feb 9, 2024

@ahaeber

/azp run

removed
pending-ci-rerunWhen assigned to a PR indicates that the CI checks should be rerun
on Feb 13, 2024
wessleym

wessleym commented on Oct 25, 2024

@wessleym

I also would appreciate if AddSession acted in the same way as AddAuthentication and AddAntiforgery. Thank you.

kvantetore

kvantetore commented on Jun 24, 2025

@kvantetore

Although I would love for the default to be more sensible, it is straight forward to use RequestPathBaseCookieBuilder to create session cookies:

services.AddSession(options =>
{
    options.Cookie = new RequestPathBaseCookieBuilder()
    {
        Name = SessionDefaults.CookieName,
        SecurePolicy = CookieSecurePolicy.None,
        SameSite = SameSiteMode.Lax,
        HttpOnly = true,
        IsEssential = false,
    };
});
dineshmike

dineshmike commented on Jun 25, 2025

@dineshmike

Although I would love for the default to be more sensible, it is straight forward to use RequestPathBaseCookieBuilder to create session cookies:

services.AddSession(options =>
{
    options.Cookie = new RequestPathBaseCookieBuilder()
    {
        Name = SessionDefaults.CookieName,
        SecurePolicy = CookieSecurePolicy.None,
        SameSite = SameSiteMode.Lax,
        HttpOnly = true,
        IsEssential = false,
    };
});

This worked for me. Thanks 🙏

kvantetore

kvantetore commented on Jun 25, 2025

@kvantetore

@wessleym, in my case, I want the session cookie to have the same path as the auth cookie, which is the root of the application. RequestPathBaseCookieBuilder does exactly that by defaulting the path to context.Request.PathBase when the Path property is null. (see https://github.com/dotnet/aspnetcore/blob/main/src/Security/Authentication/Core/src/RequestPathBaseCookieBuilder.cs#L28)

kvantetore

kvantetore commented on Jun 25, 2025

@kvantetore

@wessleym, I am not entirely sure what you are trying to achieve, but from the source code of RequestPathBaseCookieBuilder it looks like it uses context.Request.Path every time Build(...) is called.

I suppose SessionMiddleware only creates a new session cookie if a session cookie is not found in the request header. Perhaps this is where it goes wrong for you? However, I struggle to see what other behaviour would be sensible?

wessleym

wessleym commented on Jun 25, 2025

@wessleym

@kvantetore, after reading your comment and rereading the source code of RequestPathBaseCookieBuilder, I realized it does set the cookie path for every request. (I thought it just set it for the first request and reused that path later, even if PathBase had changed.) So I was wrong about that.
Your directing us to RequestPathBaseCookieBuilder is helpful. Thank you. But I still hope session can act like AddAuthentication and AddAntiforgery one day by default, as I know you do too.

added this to the Backlog milestone on Jul 29, 2025
added
area-middlewareIncludes: URL rewrite, redirect, response cache/compression, session, and other general middlewares
and removed
area-middlewareIncludes: URL rewrite, redirect, response cache/compression, session, and other general middlewares
on Jul 29, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-middlewareIncludes: URL rewrite, redirect, response cache/compression, session, and other general middlewaresbreaking-changeThis issue / pr will introduce a breaking change, when resolved / merged.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @kvantetore@ahaeber@sebastienros@Tratcher@wessleym

        Issue actions

          AddSession Sets wrong Cookie Path · Issue #48165 · dotnet/aspnetcore