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

Session with all null values on user with jwt, how does it work ? #683

Closed
2 tasks done
Mautriz opened this issue Sep 17, 2020 · 13 comments
Closed
2 tasks done

Session with all null values on user with jwt, how does it work ? #683

Mautriz opened this issue Sep 17, 2020 · 13 comments
Labels
help-needed The maintainer needs help due to time constraint/missing knowledge question Ask how to do something or how something works

Comments

@Mautriz
Copy link

Mautriz commented Sep 17, 2020

Your question
I'm using JWT, the object return by useSession is always empty (it exists, but with all null values on the user object ex: { name: null, email: null, picture: null } even tho the debug logs everything correctly.

What are you trying to do
I customized the callbacks to return the user, I expected it to this by default, it took me a while to realize how to to it

this is my code

import NextAuth, { InitOptions } from 'next-auth'
import Adapters from 'next-auth/adapters'
import Providers from 'next-auth/providers'
import { prismaClient } from '../../../../graphql/configs/prismaClient'

const options: any = {
  providers: [
    Providers.Facebook({
      clientId: process.env.FACEBOOK_CLIENT_ID,
      clientSecret: process.env.FACEBOOK_CLIENT_SECRET,
    }),
  ],
  database: process.env.DATABASE_URL,
  jwt: {
    encryption: true,
    // secret: process.env.AUTH_SECRET,
  },
  session: {
    jwt: true,
    updateAge: 1000 * 60 * 60 * 24,
  },
  secret: process.env.AUTH_SECRET,
  useSecureCookies: process.env.NODE_ENV === 'production',
  adapter: Adapters.Prisma.Adapter({ prisma: prismaClient }),
  debug: true,
 // these callbacks are what makes the user work as expected, otherwise it returns empty values
  callbacks: {
    session(session, payload) {
      if (payload.account) session.user = payload.account
      return session
    },
    jwt(token, account, user, userInfo) {
      if (userInfo) token.account = userInfo
      return token
    },
  },
}

export default (req, res) => {
  return NextAuth(req, res, options)
}

// _app.tsx
 <Provider session={pageProps.session} options={{ keepAlive: TEN_MINUTES, clientMaxAge: ONE_WEEK }}>
        <Component {...pageProps} />
   </Provider>

// index.tsx

function Home() {
  const { data, loading: queryLoading } = useMyQueryQuery({ ssr: true, fetchPolicy: 'cache-first' })
  const [session, sessionLoading] = useSession()
  return (
    <Layout>
      <Head>
        <title>Next.js × Nexus Todo App</title>
      </Head>
      {session && JSON.stringify(session)}
      {sessionLoading}
      <a href="/api/auth/signin">Sign in</a>
      <a href="/api/auth/signout">Sign out</a>
    </Layout>
  )
}

Feedback

  • [-] Found the documentation helpful // meh, kinda, the callbacks doc surely helped, but took me a while to realize I had to use them
  • Found documentation but was incomplete
  • [] Could not find relevant documentation
  • [] Found the example project helpful
  • Did not find the example project helpful // it didnt have callbacks, but worked fine appearently

Seems like a great library btw ! :D, I probably just misunderstood something I suppose

@Mautriz Mautriz added the question Ask how to do something or how something works label Sep 17, 2020
@iaincollins iaincollins added the help-needed The maintainer needs help due to time constraint/missing knowledge label Sep 22, 2020
@iaincollins
Copy link
Member

Hi @Mautriz

Thanks for sharing your issue and config!

This should actually work out of the box for name, email and picture, as per the example:

https://next-auth-example.now.sh/api-example

Facebook API

I wonder what the trigger is for this issue.

@stale
Copy link

stale bot commented Dec 5, 2020

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 ot open. Thanks!

@stale stale bot added the stale Did not receive any activity for 60 days label Dec 5, 2020
@stale
Copy link

stale bot commented Dec 12, 2020

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 Dec 12, 2020
@ChristoRibeiro
Copy link

ChristoRibeiro commented Dec 18, 2020

@iaincollins I get the same issue and seems to be related with Prisma adapter. If I remove the adapter, everything works great without callback.

@ChristoRibeiro
Copy link

ChristoRibeiro commented Dec 18, 2020

Here some tests with no user in database (pg) and no user in my Github App.

Test 1

JWT + Prisma:

 providers: [
    Providers.GitHub({
      clientId: process.env.GITHUB_ID,
      clientSecret: process.env.GITHUB_SECRET,
    }),
  ],
  secret: process.env.SECRET,
  // database: process.env.DATABASE_URL,
  adapter: Adapters.Prisma.Adapter({ prisma }),
  session: {
    jwt: true,
  },

Results:

  1. 1st signIn → Success: Session has data. JWT no data.
  2. 2nd signIn → Failure: Session has no data. JWT has no data.

Test 2

Session + Prisma

  // database: process.env.DATABASE_URL,
  adapter: Adapters.Prisma.Adapter({ prisma }),
  // session: {
  //  jwt: true,
  // },

Result: Success → Session has data.

Test 3

JWT + Typeorm:

   database: process.env.DATABASE_URL,
  // adapter: Adapters.Prisma.Adapter({ prisma }),
  session: {
    jwt: true,
  },

Result: Success → Session has data.

Conclusion

So JWT + Prisma AND isNewUser == false the token has no data. Any idea @iaincollins of why?

@balazsorban44 balazsorban44 reopened this Dec 18, 2020
@stale stale bot removed the stale Did not receive any activity for 60 days label Dec 18, 2020
@ChristoRibeiro
Copy link

ChristoRibeiro commented Dec 18, 2020

I found the error.

The function getUserByProviderAccountId from the Prisma adapter return a row from the Account table instead of the User table. So here the user variable do not contains the right data and the JWT payload can't be filled correctly.

Is it possible to have a v3.1.1 that fix this issue?

Cc @iaincollins & @balazsorban44.

@ChristoRibeiro
Copy link

ChristoRibeiro commented Dec 19, 2020

in the Prisma adapter, this should fix the issue:

- return prisma[Account].findOne({ where: { compoundId: getCompoundId(providerId, providerAccountId) } })
+ const account = await prisma[Account].findOne({ where: { compoundId: getCompoundId(providerId, providerAccountId) } })
+ if (!account) { return null }
+ return prisma[User].findOne({ where: { id: account.userId } })

@balazsorban44
Copy link
Member

balazsorban44 commented Dec 19, 2020

Hi, @ChristoRibeiro could you please create a PR with your recommended fix so it's easier to evaluate? Thank you!

@ChristoRibeiro
Copy link

The issue doesn't appear anymore on the canary branch and the deprecated prisma method findOne has been updated to findUnique. I'm not sur a PR is required. Do you plan to make a release soon @balazsorban44?

@balazsorban44
Copy link
Member

Yes, hopefully this month.

@balazsorban44
Copy link
Member

Canary has been out for a while now, try it out with npm i next-auth@canary 🎉

@lommaj
Copy link

lommaj commented Feb 24, 2021

Are we sure this is working? I am not sure if its just me but I cant seem to get JWT to work with prisma adapter, using canary.

@balazsorban44
Copy link
Member

balazsorban44 commented Feb 24, 2021

@lommaj please open a new issue or a discussion with a reproduction of your problem. I would also recommend updating to latest (which is 3.5.1 as of this writing) as. several things have been addressed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help-needed The maintainer needs help due to time constraint/missing knowledge question Ask how to do something or how something works
Projects
None yet
Development

No branches or pull requests

5 participants