Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

What is the best way to have same authentication on all subdomains? #405

Closed
2 of 5 tasks
neoromantic opened this issue Jul 7, 2020 · 15 comments
Closed
2 of 5 tasks
Labels
question Ask how to do something or how something works stale Did not receive any activity for 60 days

Comments

@neoromantic
Copy link

Your question
Is there a way and what's the best approach to have same authentication on subdomains as well as on main domain?

What are you trying to do
Suppose, I have a website, which has some subprojects on various subdomains and I'd love to have cross-domain authentication.

domain.com — my main website build on Next.js
app.domain.com — some kind of app
app2.domain.com — some other app

Some of these apps might be same Next.js app, other might be separate Next.js app.

I'd love to have same authentication for these app. So user can log in on one of these sites and become logged in on all others. Same with logout and session handling.

Can it be done with next-auth? How? What would be the best approach?

Documentation feedback

  • Found the documentation helpful
  • Found documentation but was incomplete
  • Could not find relevant documentation
  • Found the example project helpful
  • Did not find the example project helpful
@neoromantic neoromantic added the question Ask how to do something or how something works label Jul 7, 2020
@iaincollins
Copy link
Member

This a really great question! Right now, the only way to do this would be to set a custom cookie policy.

e.g. You should be able to set a 'domain' option on the 'sessionToken' cookie.

However, that should work as long as they sign in on domain.com - as you can only set cookies that work across subdomains from an apex domain (not another subdomain).

Note: This is a little awkward as you will likely want different different cookie policies in development and live - unless you are also running HTTPS in development. If using the default policy NextAuth.js does this automatically, but if you are using a custom policy you will have to handle this yourself.

We could always provide a configuration option to make this as simple as passing an option in NextAuth.js.

@saiar
Copy link

saiar commented Aug 24, 2020

We could always provide a configuration option to make this as simple as passing an option in NextAuth.js.

I already have an API server which I want to make accessible at api.domain.com and it would be great to have this option in NextAuth! Meanwhile I am trying to understand how exactly to achieve it using the options you've quoted above.

That said, @iaincollins thanks for such a fantastic library! I am moving my UI from CRA to Next JS and it was such a smooth experience to integrate Next Auth into the new application UI. What earlier tooks me 2 days was done in a matter of half an hour. And the documentation is very clean and clear too!

@ericvrp
Copy link

ericvrp commented Oct 22, 2020

Hi @iaincollins,

could you please provide the exact setting that @neoromantic would need? We have a very similar setup and usecase.

@Xodarap
Copy link
Contributor

Xodarap commented Dec 3, 2020

I've implemented this with the following and it seems to work:

const useSecureCookies = process.env.NEXTAUTH_URL.startsWith('https://')
const cookiePrefix = useSecureCookies ? '__Secure-' : ''
const hostName = Url(process.env.NEXTAUTH_URL).hostname
const options = {
  cookies: {
    sessionToken: 
    {
      name: `${cookiePrefix}next-auth.session-token`,
      options: {
        httpOnly: true,
        sameSite: 'lax',
        path: '/',
        secure: useSecureCookies,
        domain: hostName == 'localhost' ? hostName : '.' + hostName // add a . in front so that subdomains are included
      }
    },
  },
}
export default (req, res) => NextAuth(req, res, options)

Basically it's a bunch of code to add a . in front of the domain.

@iaincollins would you accept a PR to make this a flag in the options? It's a lot of work to go through for something which I think many people will want.

@iaincollins
Copy link
Member

@iaincollins would you accept a PR to make this a flag in the options? It's a lot of work to go through for something which I think many people will want.

Hey I would love a an option to set this that would then get applied to all relevant cookies set by NextAuth.js. I've been thinking about the best way for this to work.

e.g.

  1. Have people (optionally) be able to setcookies: { domain: "example.com" } or cookies: { domain: ".example.com" }
  2. Have it be a boolean option like cookies: { subdomains: true }

For context, I've also been thinking about adding support for cross-domain silent login in the longer term.

That might as a top level option like domains: [ "example.com", "example.org" ].

I've been pondering the simplest way for these options to exist to help folks avoid confusion.

If it's more like option 2. then maybe it should be a top level option and not nested inside cookies, to make it easier to find, understand and set. (e.g. just subdomains: true)

@stale
Copy link

stale bot commented Feb 1, 2021

Hi there! It looks like this issue hasn't had any activity for a while. It will be closed if no further activity occurs. If you think your issue is still relevant, feel free to comment on it to keep it open. (Read more at #912) Thanks!

@stale stale bot added the stale Did not receive any activity for 60 days label Feb 1, 2021
@stale
Copy link

stale bot commented Feb 8, 2021

Hi there! It looks like this issue hasn't had any activity for a while. To keep things tidy, I am going to close this issue for now. If you think your issue is still relevant, just leave a comment and I will reopen it. (Read more at #912) Thanks!

@stale stale bot closed this as completed Feb 8, 2021
@jjmendozabdev
Copy link

I'm having a similar issue. I tried with the cookies configuration as @Xodarap showed above and this is what I got:

app 1 running on https://abc.mydomain.com:

I successfully log in and can see the profile information. The cookie "__Secure-next-auth.session-token" is set to the domain ".mydomain.com"

app 2 running on https://xyz.mydomain.com:

The cookie is not present and even gets removed from "abc.mydomain.com" as soon as I enter to this app.

  • So, why the cookie is removed as soon as I enter to this subdomain?
  • What is the proper configuration to have this SSO across subdomains implemented? I have the next-auth library in both apps and the same configuration with the pages/api/auth/[...nextauth].ts. Is this correct?

@steven-tey
Copy link
Contributor

However, that should work as long as they sign in on domain.com - as you can only set cookies that work across subdomains from an apex domain (not another subdomain).

@iaincollins this works for my current use case – do you have an example for this? I'm a little confused by the current example in the docs – what exactly are cookiePrefix and useSecureCookies (refer below)?

pkceCodeVerifier: {
    name: `${cookiePrefix}next-auth.pkce.code_verifier`,
    options: {
      httpOnly: true,
      sameSite: 'lax',
      path: '/',
      secure: useSecureCookies
    }
  }

Also, should we insert this code snippet under [...nextauth].ts?

Thanks in advance!

@hirenr
Copy link

hirenr commented Jul 13, 2021

I'm having a similar issue. I tried with the cookies configuration as @Xodarap showed above and this is what I got:

app 1 running on https://abc.mydomain.com:

I successfully log in and can see the profile information. The cookie "__Secure-next-auth.session-token" is set to the domain ".mydomain.com"

app 2 running on https://xyz.mydomain.com:

The cookie is not present and even gets removed from "abc.mydomain.com" as soon as I enter to this app.

  • So, why the cookie is removed as soon as I enter to this subdomain?
  • What is the proper configuration to have this SSO across subdomains implemented? I have the next-auth library in both apps and the same configuration with the pages/api/auth/[...nextauth].ts. Is this correct?

Did you ever figure this out? I am currently trying exactly the same thing!!

@steven-tey
Copy link
Contributor

Quick update:

@balazsorban44 released this example that allows Next-Auth to persist auth state across different subdomains: https://github.com/vercel/examples/tree/main/solutions/subdomain-auth

@RayBans2111
Copy link

Hello! I've managed to follow this thread to solve my issue with getting my custom cookie to work with my subdomains. However, I am stuck at the moment trying to figure out how to renew an expired cookie on a subdomain that is not hosting the next-auth code. is this possible, or am I heading into uncharted waters?

I figured with renewing the cookie on the subdomain that hosts the next-auth code, I can quickly check the cookie, and redirect my user to the sign in page to sign in and get a new cookie. however, in my app that resides on a subdomain, I'm unsure how to go about checking whether my cookie is expired, and how to go about refreshing it.

one solution may be to have the user redirected to the sign in page, but it might not feel like good 'ux'.

@crisgarlez
Copy link

I'm having a similar issue. I tried with the cookies configuration as @Xodarap showed above and this is what I got:

app 1 running on https://abc.mydomain.com:

I successfully log in and can see the profile information. The cookie "__Secure-next-auth.session-token" is set to the domain ".mydomain.com"

app 2 running on https://xyz.mydomain.com:

The cookie is not present and even gets removed from "abc.mydomain.com" as soon as I enter to this app.

  • So, why the cookie is removed as soon as I enter to this subdomain?
  • What is the proper configuration to have this SSO across subdomains implemented? I have the next-auth library in both apps and the same configuration with the pages/api/auth/[...nextauth].ts. Is this correct?

I'm having the same problem with subdirectories

app1 -> mydomain.com/abc

app2 -> mydomain.com/xyz

The cookie is removed from "mydomain.com/abc" as soon as I enter to "mydomain.com/xyz"

Any solution?

@ekeric13
Copy link

ekeric13 commented Feb 26, 2023

@steven-tey that example is great for subdomains, but is there anything for cross site domains?

Specifically in development I have a backend server at 0.0.0.0 and then next.js is at localhost (127.0.0.1). I want to set a cookie to have a domain of 0.0.0.0.

I am setting my own cookie for a custom backend in a next-auth callback to have the domain of 0.0.0.0 but it never gets set.

When I do

        setCookie(apiCookieKey, authCookieValue.value, {
          req,
          res,
          maxAge: authCookieValue.maxAge,
          path: authCookieValue.path,
          sameSite: authCookieValue.sameSite as sameSiteType,
          httpOnly: authCookieValue.httpOnly,
          domain: '0.0.0.0',
        });

nothing appears in my browser.

It seems that I can only set a cookie with the domain of the like cookies.sessionToken.options. domain

@lassegit
Copy link

Is there an easy to way to update users domain to domain after they already have been set? Other than re-authenticating of course 🤔.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Ask how to do something or how something works stale Did not receive any activity for 60 days
Projects
None yet
Development

No branches or pull requests