简体   繁体   中英

ASP.NET Identity Cookie not being saved/set in subdomain

Editing to add in extra details.

I have a web project that I effectively use as an authorization server (eg example.com). I then have a few web sites that sit as sub domains (eg sub1.example.com, sub2.example.com). I am currently unable to get the .AspNet.Cookies cookie to save on the subdomains when logging in to the authorization server. I can see the cookie come back in the response but it's not being set.

I have searched and tried various solutions such as setting the CookiePath and CookieDomain . I have verified the Machine Key in the Web.config file matches between all sites. This is currently how I am enabling Cookie Authentication:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    LoginPath = new PathString("/Account/Login"),
    CookieDomain = ".example.com",
});

I have CORS enabled on the authorization server and I am able to receive the Bearer token when I log in, I just can't seem to get the cookie to be saved.

Thanks in advance.

Edit: I read somewhere that the ARRAffinity cookie could mess with things so I disabled that as well. I am still unable to see the cookie in the subdomain.

Edit 2: Adding the ajax call as requested in the comments (password and domain have been altered for consistency with the post):

$.ajax({
    url: 'https://example.com/auth/token',
    method: 'POST',
    data: {
        grant_type: 'password',
        username: 'admin@example.com',
        password: '************'
    },
    crossDomain: true
});

I'm going to take a shot at the answer here.

By default, when making cross-site ajax requests, browsers will ignore cookies. More information on this here .

To allow the use of cookies, you must set withCredentials to true in your requests, like so (more information here ):

$.ajax({
   url: 'https://example.com/auth/token',
   method: 'POST',
   data: {
      grant_type: 'password',
      username: 'admin@example.com',
      password: '************'
   },
   crossDomain: true,
   xhrFields: {
       withCredentials: true
   }
});

I've tested this locally and this should be enough if the only thing you need is to authenticate with example.com and then keep using the cookie while interacting with sub1.example.com .

If you also want to make a request with the cookie to example.com and do not want to have your responses ignored by the browser, according to this link you should make sure that example.com also returns the header Access-Control-Allow-Credentials: true .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM