dotnet / dotnet/aspnetcore

AddSession Sets wrong Cookie Path

Open
#48,165 9 comments 2 reactions 0 assignees View on GitHub
area-middleware breaking-change
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 10h
Merged PRs (30d)
281

Description

### Is there an existing issue for this?

- [X] 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.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.