cookiescross-domainnext.jsnext-auth

Authentication across across multiple domains (CORS) with NextAuth


I want to do an XHR from domain1.com to domain2.com. domain2.com is a NextJS app using NextAuth.

The problem is that when I do this request, domain2's cookies aren't included. My code is:

var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function(){
  if (httpRequest.readyState === XMLHttpRequest.DONE) {
    if (httpRequest.status === 200) {
      alert('send successful')
    } else {
      alert('Error:' + httpRequest.responseText)
    }
  }
};
httpRequest.withCredentials = true;
httpRequest.open('GET', url, true);
httpRequest.send();

Server code:

  const session = await getSession({ req })
  if(session == undefined || session.accessToken == undefined) { 
    res.statusCode = 500;
    res.send(JSON.stringify({'error': 'Not logged in'}));
    return;
  }

How can I do this?


Solution

  • Unfortunately, this isn't explicitly supported in NextAuth.js at the moment.

    You can set custom cookie policies to support subdomains (e.g. auth.example.com, www.example.com, cdn.example.com) but for entirely unique domains currently you would need to set up different sites for each domain.

    This is supported by some platforms like Auth0 as 'silent login', usually involving cross domain iframes to pass messages between sites on different domains (with one domain being 'canonical'). This a planned feature by probably not likely to drop before the end of the year.

    Note: For some OAuth providers you can use different domains with the same OAuth Client/Secret, but that's not the case for all providers, however if you are using only providers that support this, you could point all instances at the same database.

    PS: If you are interested how to do this, technically it's possible implement this yourself (with or without NextAuth.js) using the postMessage API to return a token from an off screen iframe which points to a page on a 'canonical' URL you choose for sign in; and then you could then read that token to determine if a user has a session.

    It's not too tricky to do. Where it gets complicated is doing this securely as what that means depends on the scenario (e.g. is it one web app with multiple valid domains and possibly different content, or is multiple entirely separate sites on different domains and would you be happy with client side only cookies). This is a tricky one to provide a single solution that works well for everyone and I'm not actually sure what this will look like in NextAuth.js yet.