next-auth icon indicating copy to clipboard operation
next-auth copied to clipboard

Try signing with a different account. - Callback error

Open cheesequest opened this issue 3 years ago • 32 comments

Describe the bug When trying to sign in to GitHub it says "Try signing with a different account."

Steps to reproduce

  • Clone orangopus/libby
  • click "Login"
  • Click "Sign in with GitHub"

Make sure to include the client ID and secret in .env as GITHUB_ID and GITHUB_SECRET

Expected behavior I expected it to login and return to the app.

Screenshots or error logs The error is browser_7MIk0bI7BK

Feedback Documentation refers to searching through online documentation, code comments and issue history. The example project refers to next-auth-example.

  • [x] Found the documentation helpful
  • [ ] Found documentation but was incomplete
  • [ ] Could not find relevant documentation
  • [x] Found the example project helpful
  • [ ] Did not find the example project helpful

cheesequest avatar Jan 14 '21 00:01 cheesequest

~Please provide more context, (preferably a full reproduction repository with a link) otherwise we cannot help you.~

My bad! I can see you added information about a repository, it was just hard to catch not being a link. 😅 Sorry. I'll check it out

balazsorban44 avatar Jan 14 '21 01:01 balazsorban44

Could you maybe set debug: true in your NextAuth options, and see if anything useful comes up in your console then? Also, what's the url of the page you are seeing the "Sign in with a different account" warning on?

balazsorban44 avatar Jan 14 '21 01:01 balazsorban44

Could you maybe set debug: true in your NextAuth options, and see if anything useful comes up in your console then? Also, what's the url of the page you are seeing the "Sign in with a different account" warning on?

Found the issue! User was already created so it was throwing an error.

[next-auth][error][oauth_callback_handler_error] PrismaClientKnownRequestError2 [PrismaClientKnownRequestError]: 
Invalid `prisma.user.create()` invocation:


  Unique constraint failed on the fields: (`name`)
    at PrismaClientFetcher.request (E:\libby\libby-web\node_modules\@prisma\client\runtime\index.js:78130:15)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:93:5) {
  code: 'P2002',
  clientVersion: '2.14.0',
  meta: { target: [ 'name' ] }
}

Fixed this but getting a new error now...

[next-auth][error][session_error] TypeError: Cannot read property 'name' of null
    at E:\libby\libby-web\node_modules\next-auth\dist\server\routes\session.js:99:26
    at Generator.next (<anonymous>)
    at asyncGeneratorStep (E:\libby\libby-web\node_modules\next-auth\dist\server\routes\session.js:22:103)
    at _next (E:\libby\libby-web\node_modules\next-auth\dist\server\routes\session.js:24:194)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
https://next-auth.js.org/errors#session_error

when logging out and back in.

cheesequest avatar Jan 14 '21 07:01 cheesequest

Still getting the session error. Any updates?

cheesequest avatar Jan 14 '21 21:01 cheesequest

Experiencing this as well. Ref: #1119

ovo avatar Jan 16 '21 19:01 ovo

I went to bed, woke up, booted up my app and I started getting this error. It was working last night so not sure what happened.

[next-auth][error][oauth_callback_handler_error] PrismaClientKnownRequestError2 [PrismaClientKnownRequestError]: 
Invalid `prisma.user.create()` invocation:

Unique constraint failed on the fields: (`name`)
    at PrismaClientFetcher.request (/Users/adam/Development/nextjs/hackernews/node_modules/@prisma/client/runtime/index.js:78130:15)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:93:5) {
  code: 'P2002',
  clientVersion: '2.14.0',
  meta: { target: [ 'name' ] }
} 
https://next-auth.js.org/errors#oauth_callback_handler_error

ghost avatar Jan 18 '21 22:01 ghost

@williamluke4 this seems to be Prisma related. Any ideas?

balazsorban44 avatar Jan 30 '21 21:01 balazsorban44

I'm experiencing the same problem now for no apparent reason. I'm using the Prisma client :)

typeofweb avatar Feb 26 '21 10:02 typeofweb

Could someone who is experiencing this issue please post your Prisma schema and indicate whether you are using the stock nextauthjs/next-auth prisma adapter or the adapter from nextauthjs/adapters

williamluke4 avatar Mar 02 '21 15:03 williamluke4

I am facing the same problem. I am using the Prisma Adapter.

adapter: Adapters.Prisma.Adapter({ prisma })

Prisma Schema


generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "sqlite"
  url      = "file:./dev.db"
}

model Account {
  id                 Int       @default(autoincrement()) @id
  compoundId         String    @unique @map(name: "compound_id")
  userId             Int       @map(name: "user_id")
  providerType       String    @map(name: "provider_type")
  providerId         String    @map(name: "provider_id")
  providerAccountId  String    @map(name: "provider_account_id")
  refreshToken       String?   @map(name: "refresh_token")
  accessToken        String?   @map(name: "access_token")
  accessTokenExpires DateTime? @map(name: "access_token_expires")
  createdAt          DateTime  @default(now()) @map(name: "created_at")
  updatedAt          DateTime  @default(now()) @map(name: "updated_at")

  @@index([providerAccountId], name: "providerAccountId")
  @@index([providerId], name: "providerId")
  @@index([userId], name: "userId")

  @@map(name: "accounts")
}

model Session {
  id           Int      @default(autoincrement()) @id
  userId       Int      @map(name: "user_id")
  expires      DateTime
  sessionToken String   @unique @map(name: "session_token")
  accessToken  String   @unique @map(name: "access_token")
  createdAt    DateTime @default(now()) @map(name: "created_at")
  updatedAt    DateTime @default(now()) @map(name: "updated_at")

  @@map(name: "sessions")
}

model User {
  id            Int       @default(autoincrement()) @id
  name          String?
  email         String?   @unique
  emailVerified DateTime? @map(name: "email_verified")
  image         String?
  createdAt     DateTime  @default(now()) @map(name: "created_at")
  updatedAt     DateTime  @default(now()) @map(name: "updated_at")

  @@map(name: "users")
}

model VerificationRequest {
  id         Int      @default(autoincrement()) @id
  identifier String
  token      String   @unique
  expires    DateTime
  createdAt  DateTime  @default(now()) @map(name: "created_at")
  updatedAt  DateTime  @default(now()) @map(name: "updated_at")

  @@map(name: "verification_requests")
}

kailoon avatar Apr 13 '21 23:04 kailoon

Guys, I found out a simple solution for those who struggle with email auth. Just add a callback for signin and assign a user name there. Prisma will consume that name and user will be registered.

const options = {
  callback: {
    signIn(user, account, profile) {
        user.name = slug(user.email.slice(0, user.email.indexOf('@'))) // or whatever else
  
        return true
      }
  }
}

talentlessguy avatar Apr 24 '21 18:04 talentlessguy

@williamluke4 anything to do here from our side?

ndom91 avatar Jun 07 '21 20:06 ndom91

I am also facing this issue, and I am using the prisma client with Github OAuth

bhatvikrant avatar Jun 14 '21 00:06 bhatvikrant

Hey, @bhatvikrant Do you have a reproduction I can look at?

From the above :point_up: errors it seems that the adapter is trying to create a new user but there is a unique constraint violation on the field name. Meaning that a user with that name already exists.

williamluke4 avatar Jun 14 '21 13:06 williamluke4

Hey @williamluke4, I have currently stripped out nextauthjs from my application, but I'll set it up again in a separate branch on a public repo for you to look at. Please allow me a few hours, I will update you here.

NOTE: I can confirm one thing that no user record was added in my postgres db (on heroku), however the user did get registered on the github OAuth service.

bhatvikrant avatar Jun 14 '21 13:06 bhatvikrant

Thanks, @bhatvikrant, I'll check it out when you are ready :)

williamluke4 avatar Jun 14 '21 13:06 williamluke4

This is the code for a reproducible example @williamluke4

NOTE: The github oAuth on vercel preview deployment won't work since I have not added the github and my database environment variables in the vercel environment, but you can add your own environment variables for testing. Please let me know if I should add them.

Steps I took to setup nextauthjs in this project:

  1. ran yarn add next-auth

  2. Followed the steps in this guide to install next-auth/prisma-adapter@canary

  3. added database: process.env.DATABASE_URL in [...nextauth].js file

  4. This is how my github OAuth application registration looks like Screenshot 2021-06-14 at 8 25 44 PM

  5. added GITHUB_ID, GITHUB_SECRET, DATABASE_URL environment variables in .env.local

  6. import { signOut, useSession } from 'next-auth/client' used in src/components/Navbar/index.tsx for checking session usage.

  7. import { signIn } from 'next-auth/client' used in src/components/Auth/OAuthProviders.tsx for signing in.

  8. After doing all this, I start the next server using yarn dev

  9. then, go to http://localhost:3000/login, then click on github, that redirects me to http://localhost:3000/api/auth/signin

  10. then I click on Sign in with Github, login with my github credentials and then I get this error: Screenshot 2021-06-14 at 8 46 24 PM

  11. In the nextjs server console, I get the following error Screenshot 2021-06-14 at 8 47 56 PM

Thankyou @williamluke4 for helping out :)

bhatvikrant avatar Jun 14 '21 15:06 bhatvikrant

Thanks @bhatvikrant, I'll have a dig around tomorrow morning

williamluke4 avatar Jun 14 '21 15:06 williamluke4

So there are quite a few different issues stuffed into this issue.

@bhatvikrant Your issue is because the GitHub providerAccountId given to the adapter is a number and in the database expects a string.

I don't know if this is expected behaviour and whether it should be fixed in the adapter or in the provider (@ndom91 @balazsorban44 ).

I've opened a draft PR that will ensure that the providerAccountId is converted to a string.

williamluke4 avatar Jun 15 '21 07:06 williamluke4

Hey william, thanks for this!

You probably saw it, but theres an issue/PR related to this in the core repo already as well: https://github.com/nextauthjs/next-auth/pull/2108 + https://github.com/nextauthjs/adapters/issues/130

Balazs initially said he wanted to hold off on this change until the next major release since it seems like a breaking change. Some users will have already coded around it expecting it to be a number instead of a string, etc.

How do you see it? Would this be a breaking change in your opinion?

EDIT: Someone posted a workaround in that thread:

I'll leave this note here for the benefit of other people who might run into the same issue.

Until this gets fixed, use this workaround:

import NextAuth, { User as NextAuthUser } from 'next-auth' interface NextAuthUserWithStringId extends NextAuthUser { id: string }

Providers.GitHub({
      clientId: process.env.GITHUB_ID,
      clientSecret: process.env.GITHUB_SECRET,
      profile(profile) {
        return {
          id: profile.id.toString(),
          name: profile.name || profile.login,
          email: profile.email,
          image: profile.avatar_url,
        } as NextAuthUserWithStringId
      },
    }),

ndom91 avatar Jun 15 '21 08:06 ndom91

Awesome! Thankyou @williamluke4 and @ndom91! This works for me now!

But whenever I login using github as mentioned above, the email is stored as null in my database, how can I enable email to be stored as well as soon as someone logs in?

Screenshot 2021-06-15 at 8 20 19 PM

EDIT: I can see that the docs mention: Email address is not returned if privacy settings are enabled.

bhatvikrant avatar Jun 15 '21 14:06 bhatvikrant

@ndom91 Since the prisma adapter (non-legacy version) is marked as experimental, why not use @williamluke4's PR as a temporary measure until the version of nextauth with the updated github provider is available? At that point you could undo the changes, or keep them to allow backwards compatibility with older versions of nextauth with the incompatible github provider code?

freerg avatar Jun 16 '21 01:06 freerg

I fixed this by removing the database: process.env.DATABASE_URL, that is there by default in [...nextauth].js if you copiedd it from the tutorial.

spaceclottey avatar Aug 07 '21 14:08 spaceclottey

I fixed this by removing the database: process.env.DATABASE_URL, that is there by default in [...nextauth].js if you copiedd it from the tutorial.

Same here.

EugeneGohh avatar Sep 16 '21 16:09 EugeneGohh

removed database line. still getting error

DANISHPANDITA avatar Sep 17 '21 14:09 DANISHPANDITA

Looks like the return from the git hub provider has an extra value that is not in the example prisma schema. I added refresh_token_expires_in Int? to my accont model so it looks like

model Account {
  id                 String  @id @default(cuid())
  userId             String
  type               String
  provider           String
  providerAccountId  String
  refresh_token      String?
  access_token       String?
  expires_at         Int?
  token_type         String?
  scope              String?
  id_token           String?
  session_state      String?
  oauth_token_secret String?
  oauth_token        String?
  refresh_token_expires_in        Int?

  user User @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@unique([provider, providerAccountId])
}

accont creation from git hub work for me after this

robinMcA avatar Sep 19 '21 03:09 robinMcA

The problem seems to be with the model provided on the page for PRISMA adapter, the fix (or hack) if it was missed, is to added the a new field like:

model Account {
...
refresh_token_expires_in Int?
}

Do the migrations and make sure that in DB the user/account does not already exist and then try out.

And now, No error like before as name: 'LinkAccountError' - the first time you log in, but your NOT logged in since of error, the USER row is created but NOT the ACCOUNT row and therefore the second time you try, you get the error as OAuthAccountNotLinked since now the second time the user is already present and auto account linking is NOT provided by default in next-auth

[next-auth][error][OAUTH_CALLBACK_HANDLER_ERROR] 
https://next-auth.js.org/errors#oauth_callback_handler_error 
Invalid `prisma.account.create()` invocation:

{
  data: {
    provider: 'github',
    type: 'oauth',
    providerAccountId: 'ACCOUNT ID',
    access_token: 'HIDDEN,
    expires_at: 1632613683,
    refresh_token: 'HIDDEN',
    refresh_token_expires_in: 15638400,
    ~~~~~~~~~~~~~~~~~~~~~~~~
    token_type: 'bearer',
    scope: '',
    userId: 'ckldkjbfsdkjlfdefbsdfb2'
  }
}

Part of my related dependencies:

  "dependencies": {
    "@next-auth/prisma-adapter": "^0.5.2-next.15",
    "@prisma/client": "^2.30.3",
    "next": "11.1.2",
    "next-auth": "4.0.0-beta.2",
},
"devDependencies": {
    "prisma": "^2.30.3"
  }

NOTE: Though this fixed the issue, but the behavior is somewhat weird, I used the same exact application, at one place I am getting this error and on second instance I am not. The only difference being that the first application used sqlit and second uses postgres but even on changing postgres back to sqlite on the second instance the error remains the same, so even if the problem is solved or hacked, I am not able to justify myself as to why on first instance with sqlite this is running without this new field (refresh_token_expires_in)

trulymittal avatar Sep 25 '21 16:09 trulymittal

Hey william, thanks for this!

You probably saw it, but theres an issue/PR related to this in the core repo already as well: nextauthjs/next-auth#2108 + nextauthjs/adapters#130

Balazs initially said he wanted to hold off on this change until the next major release since it seems like a breaking change. Some users will have already coded around it expecting it to be a number instead of a string, etc.

How do you see it? Would this be a breaking change in your opinion?

EDIT: Someone posted a workaround in that thread:

I'll leave this note here for the benefit of other people who might run into the same issue. Until this gets fixed, use this workaround: import NextAuth, { User as NextAuthUser } from 'next-auth' interface NextAuthUserWithStringId extends NextAuthUser { id: string }

Providers.GitHub({
      clientId: process.env.GITHUB_ID,
      clientSecret: process.env.GITHUB_SECRET,
      profile(profile) {
        return {
          id: profile.id.toString(),
          name: profile.name || profile.login,
          email: profile.email,
          image: profile.avatar_url,
        } as NextAuthUserWithStringId
      },
    }),

@ndom91 how would I write this is in .js version of the next-auth file? running into this same issue. works perfectly in dev but gives me this problem when deployed in production. :'(

amisir0219 avatar Nov 05 '21 10:11 amisir0219

nextauthjs/next-auth has been migrated to a monorepository. The adapters code can now be found there under packages/adapter-*. Thanks for your interest in the project!

ndom91 avatar Feb 04 '22 20:02 ndom91

Hey @trulymittal not sure if you've resolved this already but nonetheless I was running into this exact issue. After digging around closed issues I found this Account schema that is working well for me: https://github.com/nextauthjs/next-auth/issues/3465#issuecomment-997005276

No weird issues yet! 🤞

Seth-McKilla avatar May 25 '22 14:05 Seth-McKilla