I am seeing behavior of cookies change in my ASP.NET Core app based on adding an AuthorizeFilter and can't figure out why.
I'll try to explain as succinctly as I can. I created a sample app to illustrate it.
In the Index() of my HomeController of my test app, I have the following code, which sets a http cookie then redirects to the Index() of TestController.
public IActionResult Index()
{
CookieOptions option = new CookieOptions
{
Expires = DateTime.Now.AddDays(3650),
SameSite = SameSiteMode.Strict,
Secure = false,
HttpOnly = true
};
Response.Cookies.Append("TestCookie", "ZZZ", option);
return RedirectToAction("Index", "Test");
}
In the view of "Test", it simply displays the value of TestCookie.
<h1>TestView</h1>
<p>
@Context.Request.Cookies["TestCookie"]
</p>
If the app has no authentication, when I run it, I see "ZZZ" on the TestView page.
Then I add authentication to the app, using Microsoft Identity, putting this in Startup.cs
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAD(options => Configuration.Bind("AzureAd", options));
services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
This is code VS 2019 adds to Startup.cs when you choose Microsoft Identity when creating the project.
Now when I run the app, it does not show the value of the cookie after it redirects to the Test controller. It's empty. WHY?
Oddly, Chrome shows that it sees the cookie, but it's not seen on the server side.
If I put a breakpoint on Index() in the HomeController, it does execute the code that sets the cookie.
But a breakpoint on the CSHTML file on the line above that outputs the value of the cookie in the Test view shows that there is only one cookie in the collection, ".AspNetCore.AzureADCookie". My cookie is not there.
If I reload the page in the browser - not refresh, but hit the URL again - then it shows the cookie value.
If I comment this code out in Startup.cs, it then works as I expect it - it displays the value of the cookie in the view:
services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
I replace it with just:
services.AddControllersWithViews();
And all works as expected - so it seems to be adding the policy with AuthorizeFilter() that is affecting this.
Why is that? Why is it not saving the cookie (or losing it)?