You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

ASP.NET Core 2.2 身份验证Cookie随机丢失问题求助

Hey there, let's dig into this frustrating random cookie issue you've been stuck with for 3 months—cross-site redirects can be tricky with auth cookies, especially when the problem is intermittent. Let's break down possible causes and fixes based on your setup and code.

Looking at your ConfigureApplicationCookie setup, a few key points stand out that might contribute to the random loss:

services.ConfigureApplicationCookie(options => {
    options.Cookie.HttpOnly = true;
    options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
    options.Cookie.SameSite = SameSiteMode.Lax;
    options.Cookie.Name = "MYIDENTITY";
    options.Cookie.IsEssential = true;
    options.LoginPath = "/Account/Login";
    options.ExpireTimeSpan = TimeSpan.FromDays(3);
    options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
    options.SlidingExpiration = true;
});

Possible Causes & Fixes

Your current SameSiteMode.Lax allows cookies to be sent in cross-site GET requests, but some edge cases (like certain older browser versions, or if Survey.com uses a POST redirect back to your site) might block the cookie.

Fix:
If your site uses HTTPS (which it should for production), switch to SameSiteMode.None and enforce SecurePolicy.Always to ensure the cookie is only sent over HTTPS. Browsers require SameSite=None to be paired with Secure to prevent insecure usage:

services.ConfigureApplicationCookie(options => {
    // Keep your existing settings
    options.Cookie.HttpOnly = true;
    options.Cookie.Name = "MYIDENTITY";
    options.Cookie.IsEssential = true;
    options.LoginPath = "/Account/Login";
    options.ExpireTimeSpan = TimeSpan.FromDays(3);
    options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
    options.SlidingExpiration = true;

    // Updated settings for cross-site compatibility
    options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
    options.Cookie.SameSite = SameSiteMode.None;
});

Note: If your site isn't using HTTPS yet, you'll need to enable it first—SameSite.None won't work with HTTP.

2. Data Protection Key Misconfiguration (Critical for Multi-Server Setups)

If your app runs on multiple servers (e.g., load-balanced), each server uses its own default data protection key by default. When a user logs in on Server A, the cookie is encrypted with Server A's key. If they redirect back to Server B, Server B can't decrypt the cookie, so it acts like the cookie doesn't exist—this causes random failures depending on which server handles the return request.

Fix:
Configure shared data protection keys across all servers. For example, using SQL Server to store keys:

  1. Install the required NuGet package:

    Install-Package Microsoft.AspNetCore.DataProtection.SqlServer
    
  2. Add this to your ConfigureServices method:

    services.AddDataProtection()
        .PersistKeysToSqlServer(new SqlConnection("Your_Database_Connection_String"))
        .SetApplicationName("YourAppUniqueName"); // Use the same name across all servers
    

This ensures all servers use the same encryption keys, so cookies are decryptable regardless of which server handles the request.

Browsers have limits on the number and size of cookies stored per domain. If your site sets multiple cookies, or if the MYIDENTITY cookie grows too large, browsers might randomly evict cookies when hitting limits.

Fix:

  • Use browser dev tools (F12 → Application → Cookies) to check the size of MYIDENTITY and how many cookies your domain has.
  • If the cookie is oversized, reduce the amount of data stored in the auth cookie (e.g., avoid adding excessive user claims that aren't necessary).

4. ASP.NET Core 2.2 SameSite Bugs

ASP.NET Core 2.2 has known issues with SameSite cookie handling, especially around cross-site scenarios. Later versions (3.1+) fixed many of these bugs.

Fix:
Consider upgrading your ASP.NET Core version to 3.1 or higher. Angular 10 is compatible with newer ASP.NET Core versions, though you'll need to test for any minor breaking changes.

5. Debugging to Pinpoint the Issue

Since the problem is random, you'll need to capture data when it happens:

  • Use browser dev tools (Network tab) to check if the MYIDENTITY cookie is being sent in the request when returning from Survey.com.
  • Check your server logs for authentication errors (e.g., "Failed to decrypt cookie" or "No authentication cookie found").
  • Use Fiddler to capture the full request/response flow when the issue occurs—this will show if the cookie is missing from the request, or if the server is rejecting it.

Final Notes

Start with the data protection key check if you're on multiple servers—that's a common cause of random auth failures. If you're on a single server, try adjusting the SameSite and Secure settings first.

Don't forget to test each change thoroughly since the issue is intermittent—you might need to replicate the cross-site flow multiple times to confirm if the fix works.

内容的提问来源于stack exchange,提问作者Jinseong Kim

火山引擎 最新活动