'How to make general cookie authentication for 2 asp.net core apps?

I have 2 asp.net core webapis under 1 subdomain, and I'm going to add cookie authentication to one of them based on first api, but it doesn't working. It can't parse cookies from other one. I read some articles about this point, but is didn't help. One of them

  1. Sharing Cookies Between Two ASP.NET Core Applications
  2. https://docs.microsoft.com/en-us/aspnet/core/security/cookie-sharing?view=aspnetcore-6.0

Info about APIs

  1. Using .NET 6, cookie authentication with ASP.NET Core Identity, authentication works fine

    builder.Services.AddIdentity<User.Repository.Entities.User, 
    IdentityRole>(options =>
    {
        options.Password.RequireDigit = false;
        options.SignIn.RequireConfirmedEmail = true;
    })
    .AddEntityFrameworkStores<UserDbContext>()
    .AddDefaultTokenProviders();
    
    builder.Services.ConfigureApplicationCookie(options =>
    {
        options.Cookie.Name = "Custom.Identity";
        options.Cookie.Domain = "custom.com";
        options.Events.OnValidatePrincipal = context =>
        {
            context.Response.StatusCode = StatusCodes.Status401Unauthorized;
            return Task.CompletedTask;
        };
    });
    builder.Services.AddDataProtection()
                    .PersistKeysToFileSystem(new DirectoryInfo("c:\\security-keys"))
                    .SetApplicationName("SharedCookieApp");
    
    builder.Services
        .AddAuthentication()
    
  2. Using asp.net core 3, used jwt token auth before, I want to add cookie auth there without ASP.NET Core Identity; Authentication always fails with cookies from first API

        services.AddDataProtection()
            .PersistKeysToFileSystem(new DirectoryInfo("c:\\security-keys"))
            .SetApplicationName("SharedCookieApp");
    
        services.AddAuthentication(options =>
        {
    
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        })
            .AddCookie(options =>
            {
                options.Cookie.Name = "Custom.Identity";
                options.Cookie.Domain = "custom.com";
    
                options.Events.OnValidatePrincipal = context =>
                {
                    context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                    return Task.CompletedTask;
                };
            });
    

P.S. Records from failed API logs.

    Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[7]
          Cookies was not authenticated. Failure message: Unprotect ticket failed

Anybody knows the possible reason of auth failing?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source