Cookie(OICD authentication) is not removed when Browser is closed in ASP.NET Core App

Tapsa 0 Reputation points
2023-03-15T08:11:06.07+00:00

Hello,

I have an older ASP.NET Core App that uses OICD Authentication and it's Cookie.

Problem is that when old .NET Core 2.1 was updated to .NET Core 3.1 that Cookie stayed to live in Browser although Browser was closed. E.g. Logging into App and then closing the Browser and then Logging again didn't succeeded.

Only way get rid of this problem is to delete Cookie by hand in Browser's Development tools.

I was thinking that problem might be in Application's Startup.cs file and it's Authentication and Cookie settings code.

Has anyone noticed that same problem when upgrading .NET Core 2.1 to .NET Core 3.1? What could be wrong in Authentication/Cookie code (code below) and what should be changed? Thanks!

services.AddAuthentication(options =>
{
	options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
	options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
	options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
	options.Cookie = new Microsoft.AspNetCore.Http.CookieBuilder()
	{
		SecurePolicy = Microsoft.AspNetCore.Http.CookieSecurePolicy.Always,
		HttpOnly = true,
		SameSite = Microsoft.AspNetCore.Http.SameSiteMode.None
	};
})
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
	options.Authority = Configuration.GetSection("AppConfiguration")["AADInstance"];
	options.ClientId = Configuration.GetSection("AppConfiguration")["ClientId"];
	options.ClientSecret = Configuration.GetSection("AppConfiguration")["ClientSecret"];
	options.AuthenticationMethod = OpenIdConnectRedirectBehavior.FormPost;
	options.SaveTokens = true;

	options.Events.OnTicketReceived = c =>
	{
		// Note: OICD authentication does not produce refresh token. 
		//       We need to request it separately
		var accessTokenWithBackingRefreshToken = AuthContext.AcquireTokenAsync(options.ClientId,
			new ClientCredential(options.ClientId, options.ClientSecret),
			new UserAssertion(c.Properties.GetTokenValue("id_token"))).Result;
		// Note: The refresh token is now stored to the token cache. 
		//       Next the token stored in the authentication cookie 
		//       is updated so that it can be used to access the token cache
		//       on consequtive requests.
		c.Properties.UpdateTokenValue("id_token", accessTokenWithBackingRefreshToken.AccessToken);


		return Task.CompletedTask;
	};
	
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,192 questions
{count} votes