A colleague of mine recently worked on a problem of cookie for a .NET application backend using cookie to validate some business logic. Here how it is done.
The background of the issue
The project used infrastructure based on multiple pods using Openshift and this allows load-balancing the frontend and backend.
On the project, we used Redis to store the cookies.
The problem
Without load-balancing, no issue occurred. The application set the cookies and the applications worked as attended.
When the project added load-balancing, the applications stopped working.
Why?
The solution
The cookies needed for the business logic to work were absent.
How did my colleague resolve the issue?
First by creating the session store class to handle CRUD operation in the Redis cache:
Then, my colleague added the cookie manager class as a Singleton in the extension method registering the services (public static void RegisterServices(this IServiceCollection services, IConfigurationRoot configuration, bool isTestEnvironment))
publicpartialclassProgram{privateconststringAPI_CORS_POLICY="ApiCorsPolicy";publicstaticvoidMain(string[]args){varbuilder=WebApplication.CreateBuilder(args);// Dependency Injection for Servicesbuilder.Services.RegisterServices(Configuration);// Dependency Injection for Controllersbuilder.Services.RegisterControllers(Configuration);// Register Loggersbuilder.Logging.RegisterLoggingProviders(Configuration,builder.Services);builder.AddCookie().AddOpenIdConnect(options=>{// ... some code is omitted for brevityOnTokenValidated=context=>{varidToken=context.SecurityToken.RawData;// Token IDvaraccessToken=context.SecurityToken.RawData;// Access TokenvarrefreshToken=context.SecurityToken.RawData;// Refresh TokenvarsessionId=context.Principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;varkey=$"{sessionId}:cookies:app-auth";context.HttpContext.RequestServices.GetRequiredService<ICookieManager>().AppendResponseCookie(context.HttpContext,key,accessToken,newCookieOptions());returnTask.CompletedTask;}};});varapp=builder.Build();app.Run();}}