How can I share session among subdomains in ASP.NET Core?

两盒软妹~` 提交于 2021-02-04 15:09:19

问题


I have a website which has subdomains such as ali.sarahah.com but if a user logs in from www.sarahah.com then goes to ali.sarahah.com the session is not saved. After searching I added the following in Startup.cs:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    CookieDomain = ".sarahah.com"
});

I found out that .AspNetCore.Identity.Application cookie domain is still showing the subdomain and not the the domain and that session problem is still there.

Am I doing something wrong?


回答1:


I think you need to remove the leading . in the domain assignment as detailed in this GitHub issue:

app.UseCookieAuthentication(
    new CookieAuthenticationOptions
    {
        // Note that there is no leading .
        CookieDomain = "sarahah.com",
        CookieSecure = CookieSecurePolicy.None
    });

See the CookieAuthenticationOptions for the various properties.




回答2:


I was able to solve it by adding this to ConfigureServices method in Startup.cs:

        services.AddIdentity<ApplicationUser, IdentityRole>(options =>
        {
            options.Cookies.ApplicationCookie.CookieDomain = ".yourdomain.com";
            options.Cookies.ApplicationCookie.CookieSecure = Microsoft.AspNetCore.Http.CookieSecurePolicy.None;
        })

The CookieSecure part is because my site moves between http and https in different pages.

Thank you :)




回答3:


In case someone is looking for a solution to this problem using ASP.NET Core 2.0. You can set the cookie domain via the CookieAuthenticationOptions in your ConfigureServices method when adding the authentication services.

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
            options.Cookie.Domain = ".yourdomain.com";
        });


来源:https://stackoverflow.com/questions/41872524/how-can-i-share-session-among-subdomains-in-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!