You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Identity跨子域Cookie:.NET多版本应用登录授权互通

Hey there! Let's tackle your cross-subdomain authentication and authorization scenario step by step—since you've got a mix of ASP.NET Core and .NET Framework apps, we need to make sure they can share auth tickets and recognize roles across all subdomains. Here's a practical, tested approach:

Core Foundation: Shared Auth Context

The core idea is to have all apps use shared encryption keys and a unified cross-subdomain cookie so they can decrypt and validate each other's authentication tickets.


1. Configure ASP.NET Core Apps (Website A & C)

ASP.NET Core uses Data Protection to encrypt auth cookies. Ensure both Core apps share the same key store so they can decrypt each other's cookies. For example, use a shared file system directory:

// In Startup.cs -> ConfigureServices
services.AddDataProtection()
    .SetApplicationName("YourGlobalAppName") // Same name across ALL Core apps
    .PersistKeysToFileSystem(new DirectoryInfo(@"\\your-shared-server\auth-keys")); // Shared secure directory

Identity Core (Account.example.com - Website C)

Configure the auth cookie to be accessible across all subdomains, and enable role support:

services.AddDefaultIdentity<IdentityUser>()
    .AddRoles<IdentityRole>() // Enable role management
    .AddEntityFrameworkStores<YourAuthDbContext>();

services.ConfigureApplicationCookie(options =>
{
    options.Cookie.Domain = ".example.com"; // Critical: All subdomains can access this cookie
    options.Cookie.Name = ".YourApp.AuthCookie"; // Unified cookie name for all apps
    options.LoginPath = "/Account/Login";
    options.LogoutPath = "/Account/Logout";
    options.Cookie.SecurePolicy = CookieSecurePolicy.Always; // Enforce HTTPS
    options.Cookie.SameSite = SameSiteMode.Lax; // Balance security and cross-domain usability
    options.SlidingExpiration = true;
});

ASP.NET Core 2.0 (www.example.com - Website A)

Set up authentication to consume the shared cookie:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.Cookie.Domain = ".example.com";
        options.Cookie.Name = ".YourApp.AuthCookie";
        options.ExpireTimeSpan = TimeSpan.FromHours(8);
        options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
    });

// Don't forget to add this in Configure()
app.UseAuthentication();
app.UseAuthorization();

2. Configure .NET Framework Apps (Website B & D)

Unified Machine Key

All .NET Framework apps need identical machine keys to decrypt the shared auth cookie. Add this to each app's Web.config:

<system.web>
    <machineKey 
        validationKey="YOUR_GENERATED_VALIDATION_KEY" 
        decryptionKey="YOUR_GENERATED_DECRYPTION_KEY" 
        validation="SHA1" 
        decryption="AES" />
</system.web>

Generate secure keys using aspnet_regiis.exe -pc "MyAppAuthKeys" -exp (run as admin), then export and reuse them across all Framework apps.

Forms Authentication Setup

Configure Forms Auth to match the Core cookie settings, so it can recognize the ticket from Account.example.com:

<system.web>
    <authentication mode="Forms">
        <forms 
            name=".YourApp.AuthCookie" 
            domain=".example.com" 
            loginUrl="https://account.example.com/Account/Login" 
            protection="All" 
            timeout="480" 
            slidingExpiration="true"
            requireSSL="true" /> <!-- Enforce HTTPS -->
    </authentication>
    <httpCookies sameSite="Lax" /> <!-- Match Core's SameSite setting -->
</system.web>

Role Recognition for Framework Apps

To make Framework apps read roles from the Core-generated cookie, add this to Global.asax.cs:

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
    if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
    {
        var claimsIdentity = HttpContext.Current.User.Identity as ClaimsIdentity;
        if (claimsIdentity != null)
        {
            var roles = claimsIdentity.FindAll(System.Security.Claims.ClaimTypes.Role)
                                      .Select(c => c.Value)
                                      .ToArray();
            HttpContext.Current.User = new GenericPrincipal(claimsIdentity, roles);
        }
    }
}

3. Cross-Subdomain Login Redirect Logic

When users try to access a protected page on any subdomain, redirect them to Account.example.com with a ReturnUrl parameter:

  • Example: A user visits https://site.example.com/Admin → gets redirected to https://account.example.com/Account/Login?ReturnUrl=https%3A%2F%2Fsite.example.com%2FAdmin
  • In Account.example.com's login action, after successful authentication, redirect back using Redirect(ReturnUrl)—always validate the ReturnUrl is a trusted subdomain (use Url.IsLocalUrl or a allowlist to prevent open redirects).

4. Role-Based Authorization Implementation

ASP.NET Core Apps

Use attribute-based authorization directly:

// Controller-level
[Authorize(Roles = "Admin")]
public class AdminController : Controller { ... }

// Or policy-based for more control
services.AddAuthorization(options =>
{
    options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin"));
});

// Use policy
[Authorize(Policy = "AdminOnly")]
public IActionResult AdminDashboard() { ... }

.NET Framework Apps

  • ASP.NET MVC 4.7: Use [Authorize(Roles = "Admin")] on controllers/actions.
  • ASP.NET WebForms: Add AuthorizeRoles="Admin" to the @Page directive, or check User.IsInRole("Admin") in code-behind.

Critical Notes

  • Enforce HTTPS Everywhere: All subdomains must use HTTPS—secure cookies won't work over HTTP.
  • Key Security: Never hardcode machine keys or data protection keys. Use secure storage like Azure Key Vault or encrypted config files.
  • Test Compatibility: Verify each app can read the auth cookie by checking User.Identity.Name and User.IsInRole("YourRole") in debug mode.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:10:06