3

I have 2 applications that share cookies between them. This is the configuration in both the startup.cs:

services.ConfigureApplicationCookie(options =>
{
    // Cookie settings
    options.Cookie.Name = Environment.GetEnvironmentVariable(CONST.CookieName);
    options.Cookie.SameSite = SameSiteMode.Lax;
    options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
    options.Cookie.Path = Environment.GetEnvironmentVariable(CONST.CookiePath);
    options.Cookie.Domain = Environment.GetEnvironmentVariable(CONST.CookieDomain);
    options.Cookie.HttpOnly = true;
    options.ExpireTimeSpan = TimeSpan.FromMinutes(Convert.ToDouble(Environment.GetEnvironmentVariable(CONST.CookieExpiryTimeSpanInMinutes)));

    options.LoginPath = Environment.GetEnvironmentVariable(CONST.LoginPath);
    options.AccessDeniedPath = Environment.GetEnvironmentVariable(CONST.AccessDeniedPath);
    options.SlidingExpiration = true;
});

The problem now is that if I load App A and App B together, login into App A then click login on App B, I get a Bad Request error. I tried to debug App B to check why it was getting this error and I discovered that when I am logged in to App A and try to login on App B, the Application doesn't know that I have already been authenticated.

if (User.Identity.IsAuthenticated)
{
    return LocalRedirect(returnUrl);
}

The line above is always false.

Is there a way to prevent this issue? Or is there a way to check if a cookie has already been set?

EDIT:

I have set the Data Protection Key for all the apps:

var ds = new DirectoryInfo("PathTOKey");
services.AddDataProtection()
    .PersistKeysToFileSystem(ds)
    .SetApplicationName("DPName");

EDIT:

Cookie Options in Startup.cs

services.Configure<CookiePolicyOptions>(options =>
{
    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
    options.CheckConsentNeeded = context => false;
    options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.Configure<IdentityOptions>(options =>
{
    options.Password.RequireDigit = false;
    options.Password.RequireLowercase = false;
    options.Password.RequireNonAlphanumeric = true;
    options.Password.RequireUppercase = true;
    options.Password.RequiredLength = 6;
    options.User.AllowedUserNameCharacters =
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
    options.User.RequireUniqueEmail = false;
    options.SignIn.RequireConfirmedEmail = false;
    options.SignIn.RequireConfirmedPhoneNumber = false;
    options.Lockout.AllowedForNewUsers = false;
});
var ds = new DirectoryInfo(Path.Combine(Environment.GetEnvironmentVariable(UCCASGlobals.CentralApplicationSettings), "KeyRing"));
services.AddDataProtection()
    .PersistKeysToFileSystem(ds)
    .SetApplicationName(Environment.GetEnvironmentVariable(UCCASGlobals.DataProtectionApplicationName));

services.ConfigureApplicationCookie(options =>
{
    // Cookie settings
    options.Cookie.Name = Environment.GetEnvironmentVariable(UCCASGlobals.CookieName);
    options.Cookie.SameSite = SameSiteMode.Lax;
    options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
    options.Cookie.Path = Environment.GetEnvironmentVariable(UCCASGlobals.CookiePath);
    options.Cookie.Domain = Environment.GetEnvironmentVariable(UCCASGlobals.CookieDomain);
    options.Cookie.HttpOnly = true;
    options.ExpireTimeSpan = TimeSpan.FromMinutes(Convert.ToDouble(Environment.GetEnvironmentVariable(UCCASGlobals.CookieExpiryTimeSpanInMinutes)));

    options.LoginPath = Environment.GetEnvironmentVariable(UCCASGlobals.LoginPath);
    options.AccessDeniedPath = Environment.GetEnvironmentVariable(UCCASGlobals.AccessDeniedPath);
    options.SlidingExpiration = true;
});
12
  • What happens when you load the AppA and later AppB (instead of opening together)? Does the AppB loads properly? Commented Oct 13, 2019 at 11:07
  • Hi @user1672994, when I load AppA and then AppB, it loads properly. AppB redirects to the home page without any issue. Commented Oct 14, 2019 at 1:24
  • AppB will not know if AppA is already authenticated if they share the cookies if opened together. You can redirect to login page if User.Identity.IsAuthenticated in AppB (and AppA) is false so that browser tries to login silently and set the required cookies and header to app to work. Commented Oct 14, 2019 at 5:44
  • I tried to debug AppB after AppA has logged in but I get pushed to the home page immediately and none of my login code was reached. However, I get the Bad Request error. I placed the User.identity.IsAuthenticated in my Login Page and the Submit Login function so if they are hit, it will definitely trigger. The issue is that the code isn't getting hit at all. Commented Oct 14, 2019 at 6:34
  • Can you please check what has triggered at bad request? You can put the break points in Startup where you are adding the Authentication logic. Is clicking on login page on AppB is a API request or redirect request? Commented Oct 14, 2019 at 6:38

3 Answers 3

1

Make sure that you have configured data protection in both of application and data protection keys and the app name must be the same in two Apps .

Configures the data protection system to persist keys to the specified directory. This path may be on the local machine or may point to a UNC share.

services.AddDataProtection()
         .PersistKeysToFileSystem(new DirectoryInfo(@"d:\Keys"))
         .SetApplicationName("SharedCookieApp");

services.ConfigureApplicationCookie(options => {
          options.Cookie.Name = ".AspNet.SharedCookie";
        });

You could check the cookies value by cookie name in the request

var cookie=Request.Cookies["Cookie Name"];

Reference : https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/overview?view=aspnetcore-3.0

Sign up to request clarification or add additional context in comments.

1 Comment

I have already done that. The problem is that cookies can only be loaded on a new http request. What I'm doing now is loading the 2 different web apps at the same time, logging in to one and then logging in to another one. That is the cause of my Bad Request error because the second app detects that there is already a cookie too late.
0

It's not enough to share the cookie. The cookie is encrypted, so both apps must be set up to encrypt/decrypt the same. This is done via data protection providers, and requires persisting the keyring to a common location both apps can access and ensuring that both use the same application name (which controls the segregation of keys).

services.AddDataProtection()
    .PersistKeysToFileSystem("{PATH TO COMMON KEY RING FOLDER}")
    .SetApplicationName("SharedCookieApp");

This is all in the docs.

2 Comments

My bad, I didnt add this. I actually share the cookies already. The issue is that in when I am logged in to App A, I just need to refresh the page in App B and I will be redirected to App B's homepage. However, when I am logged in to App A and I click the login button in App B, I get the error as stated above.
I need a way to check if cookies have been set when I click the login button. The User.Identity.IsAuthenticated doesn't do it/
0

I seem not be able to reproduce the BadRequest you're getting when logging in both applications at the same time. I even manually created the demo in my github: https://github.com/davidliang2008/DL.ShareCookiesApps

  • Both web apps are backed with one Identity system
  • Both web apps are configured to be protected the entire site with .RequireAuthenticatedUser() policy


When I start both applications from Visual Studio, from the screenshot below, you can tell

  • Logging into App B right after logging into App A won't throw an error
  • Logging out one of the Apps will automatically logout the other implicitly (clicking the home page will ask the user to authenticate again)
  • Logging in one of the Apps will automatically log in the other implicitly (clicking the home page will let the user in)


enter image description here

The only problem I'm encountering is when I put both sites together in one browser (I'm using latest Chrome), they will crash together. They're running fine when they're in separate browser instance.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.