Session is linked to wrong user when using OAuth

Hey everyone, I was trying to integrate a NextCloud OAuth to my Next.JS v15 application using Better-Auth. Everything is working fine, except for one little thing. When I use the OAuth login function from Better-Auth, I get authenticated and the user data is fetched from my NextCloud. I created a "profile" page to display all the user and session data, just for testing purposes. When I check the page, I always get the user, that I first signed in with. I logged in with a normal browser window and a private browser window to check the functionality. But I always get the user data that I first signed in with. When using the credentials provider that I set up, everything is working fine, only the OAuth with NextCloud is causing issues. Does anyone have an idea, what could be the problem or how I could fix it? Thank you very much!
Solution:
Found out what the issue was... Nextcloud was not giving me a valid email address through their API. Therefore the two users were created using the same email address, which let better-auth think, that they are the same user... Very stupid of me...
Jump to solution
9 Replies
Ping
Ping3mo ago
Hey I've never heard of NextCloud, are you using the Generic OAuth plugin?
KingJoYT
KingJoYTOP3mo ago
Yes
Ping
Ping3mo ago
So once you signed into to your account on NextCloud then redirected back to your app you have a valid session which you can see on your test page. However when you open an incognito window to view the test page, the session is still visible there too?
KingJoYT
KingJoYTOP3mo ago
No, the session is not visible there. I sign in to the NextCloud with another account and when I am redirected back to the application and go to the test page, I see the details from the first login, with the other account
Ping
Ping3mo ago
Can you help me test using a different browser?
KingJoYT
KingJoYTOP3mo ago
Sure Tested it with Firefox and Brave (Chrome) both showed the same result
Ping
Ping3mo ago
Can you log and see if both accounts from NextCloud return the same user id? @KingJoYT
KingJoYT
KingJoYTOP3mo ago
I'm using the getUserInfo method in the genericOAuth config to fetch the user data from the NextCloud and the data returned from the cloud is the right data. The only issue I can find is that the session in the database is always linked to the first user So to answer your question: No, they return different user ids
Solution
KingJoYT
KingJoYT3mo ago
Found out what the issue was... Nextcloud was not giving me a valid email address through their API. Therefore the two users were created using the same email address, which let better-auth think, that they are the same user... Very stupid of me

Did you find this page helpful?