1

In my Startup class public void Configure(IApplicationBuilder app...) I'm setting up my cookie authentication in a pretty standard way:

app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
CookieName = cookieName,
//CookiePath = "",
AuthenticationScheme = cookieAuthSchemeName,
}); 

But I realized I was unable to set up the CookiePath the way I wanted because I don't know how to access the host server path base at this stage. For instance if my server is listening to http://internal.net:5000/myappbase/ then I could have a controller with one action and I would like to set up my cookie path to be /myappbase/controller1 which I'm failing to do because at that stage, Startup::Configure, I can't get the information about the server listening to /myappbase. Maybe there is something injected that I could use, but I haven't found it yet.

What I've tried:

Injecting IHttpContextAccessor contextAccessor didn't help.

I known I could be getting that easily anywhere else when I'm actually treating a request base on what I've read here: How can I get the root domain URI in ASP.NET?

And I can also see that in the code of the CookieAuthenticationHandler, it is getting this information based on the Request:

protected string CurrentUri
{
    get
    {
        return Request.Scheme + "://" + Request.Host + Request.PathBase + Request.Path + Request.QueryString;
    }
}

Or

var cookieOptions = new CookieOptions
{
    Domain = Options.CookieDomain,
    HttpOnly = Options.CookieHttpOnly,
    Path = Options.CookiePath ?? (OriginalPathBase.HasValue ? OriginalPathBase.ToString() : "/"),
};

but really, in the Startup::Configure, I don't know how to do that.

Any help would be appreciated.

Community
  • 1
  • 1
Daboul
  • 2,635
  • 1
  • 16
  • 29

1 Answers1

2

In the ConfigureServices(IServiceCollection services) method, add:

services.Configure<CookiePolicyOptions>(options =>
{
    options.OnAppendCookie = (e) =>
    {
        e.CookieOptions.Path = e.Context.Request.PathBase;
    };
    .....
}); 

Note: when a cookie is created and before it is sent to the client, the path of the cookie will be set to the Request.PathBase.

Pierre.Vriens
  • 2,117
  • 75
  • 29
  • 42
Lahna200
  • 501
  • 4
  • 5
  • when a cookie is created and before it is sent to the client, the path of the cookie will be set to the Request.PathBase – Lahna200 Sep 23 '18 at 07:40