nextauthjs / next-auth

Authentication for the Web.
https://authjs.dev
ISC License
24.16k stars 3.35k forks source link

Sharing Auth Session between different nextjs projects #8068

Closed faye1225 closed 1 year ago

faye1225 commented 1 year ago

Question 💬

I have two projects using nextjs that I would like to share authcooke, deployed in vercel.

One domain is https://example.art/ and one is https://sub.example.art/.

When https://example.art/ logs in,

https://sub.example.art/ can see the session, but as soon as https://sub.example.art/ is refreshed, the https://example.art/ login status disappears

The configuration of the two projects is basically the same, this is the next.config.js

  cookies: {
    domain: '.example.art',
  },
  async headers() {
    if (process.env.NODE_ENV == 'production')
      return [
        {
          source: '/api/auth/:path*',
          has: [{ type: 'header', key: 'Origin', value: '(?<serviceName>^https://.*.example.art$)' }],
          headers: [
            { key: 'Access-Control-Allow-Credentials', value: 'true' },
            { key: 'Access-Control-Allow-Origin', value: ':origin' },
            { key: 'Access-Control-Allow-Methods', value: 'GET, OPTIONS, PATCH, DELETE, POST, PUT' },
            {
              key: 'Access-Control-Allow-Headers',
              value:
                  'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version',
            },
          ],
        },
      ]

  },

[...nextauth.ts]

export const authOptions: NextAuthOptions = {
  adapter: MongoDBAdapter(clientPromise, { databaseName: process.env.MONGODB_NAME }),
  providers: (() => {
    const final: (OAuthConfig<any> | EmailConfig)[] = [
      GoogleProvider({
        clientId: process.env.GOOGLE_CLIENT_ID,
        clientSecret: process.env.GOOGLE_CLIENT_SECRET,
        authorization: {
          params: {
            prompt: 'consent',
            access_type: 'offline',
            response_type: 'code',
          },
        },
        httpOptions: {
          timeout: 10000,
        },
        profile(profile) {
          return { ...profile, role: AuthRole.USER, avatar: profile.picture, id: profile.sub }
        },
      }),
    ]
    return final
  })(),
  session: { strategy: 'database' },
  cookies: {
    sessionToken: {
      name: `${useSecureCookies ? '__Secure-' : ''}next-auth.session-token`,
      options: {
        httpOnly: true,
        sameSite: 'lax',
        path: '/',
        domain: useSecureCookies ? '.replicable.art' : undefined,
        secure: useSecureCookies,
      },
    },
  },

}

I don't know what the problem is and how I should change it

How to reproduce ☕️

Details as above

Contributing 🙌🏽

Yes, I am willing to help answer this question in a PR

token-ed commented 7 months ago

Hey @faye1225. I'm wondering how you solved this? Having the same doubt.