Account linking does not work correctly when using JWT
See original GitHub issueDescribe the bug Signing in with email and then signing in with an OAuth provider creates two separate users when using JWT sessions.
It should be noted that I only tested this issue with an OAuth provider that does not grant access to the user’s email address
Steps to reproduce https://github.com/RobertCraigie/next-auth-multiple-user-bug
- Sign in with email
- Sign in with Bungie
Expected behavior One user is created and the OAuth account is linked to said user.
Screenshots or error logs https://imgur.com/a/sI2pNzp
Additional context I have traced the root cause of this issue to https://github.com/nextauthjs/next-auth/blob/73d21e66ddb73da968d93cec32d4b46b152e217a/src/server/lib/callback-handler.js#L55
This block of code expects the decoded JWT to have a user property when it does not.
A simple fix is to add the user property in the JWT callback
...
callbacks: {
jwt: async (token, user, account, profile, isNewUser) => {
const isSignIn = user ? true : false;
if (isSignIn) {
token.user = { id: user.id }
}
return Promise.resolve(token);
}
},
...
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
Issue Analytics
- State:
- Created 3 years ago
- Reactions:13
- Comments:6 (6 by maintainers)
Hmm I’m too tired to give you a good answer, I’ll try and remember to look at this tomorrow, but the intent from the comments seems reasonable. 😃
I appreciate what is good behaviour here is a bit fuzzy, without a one-to-many user<->email relationship, but saving an address when linking if you don’t already have one seems reasonable.
I think ideally we’d want to cherry pick the email field from the profile to add to the user object, rather than merging in the profile object, as you’d not want to override the name (if one was already specified). I think version 1.x (pre Serverless) did this too, for both email and the name field (only updating them when linking if they were not set).
We’ve just made some good progress on automating CD/CI tests today, so things should start moving quickly again soon - the main reason for not jumping on stuff like this sooner has been the pain of manual regression testing, but the OP is a great example of less common regression bug we can avoid in future by having a test case for it.
That makes sense, thank you.
However in the meantime (until a specific flow for adding/changing email addresses is added), is a solution like this safe/valid?