nextauthjs / next-auth

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

502: BAD_GATEWAY #1021

Closed ats1999 closed 3 years ago

ats1999 commented 3 years ago

502: BAD_GATEWAY While doing GitHub OAuth, i got this.

An error occurred with this application.
This is an error with the application itself, not the platform.

502: BAD_GATEWAY
Code: NO_RESPONSE_FROM_FUNCTION
ID: bom1::dc4x6-1609474836212-36479d781165

If you are a visitor, contact the website owner or try again later.
If you are the owner, check the logs for the application error.
Developer Documentation →

Reproduction visit https://bdevg.com/api/auth/signin then choose a sign with Github

Vercel function logs

[GET] /api/auth/callback/github?code=248bb9c03e85a89c3070&state=6d154f358c1546618487d1cd81bb4c1686b91a60d135507093fcbbb4930ec29b
15:20:25:95
Status:
-1
Duration:
10010.81ms
Memory Used:
74 MB
ID:
dc4x6-1609474825954-f73eb9e7144f
User Agent:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36
2021-01-01T04:20:36.092Z 02b5d489-c291-43b5-a9d3-6deff015db6a Task timed out after 10.01 seconds
[POST] /api/auth/signin/github
15:20:24:95
Status:
302
Duration:
82.08ms
Memory Used:
66 MB
ID:
dc4x6-1609474824954-55d2910131f0
User Agent:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36
[GET] /api/auth/error?error=oAuthCallback
15:19:15:43
Status:
200
Duration:
3.68ms
Memory Used:
62 MB
ID:
dc4x6-1609474755430-c761c6296b2a
User Agent:
Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36
[GET] /api/auth/error?error=oAuthCallback
15:19:15:07
Status:
200
Duration:
3.63ms
Memory Used:
62 MB
ID:
dc4x6-1609474755070-1bd8ee28d530
User Agent:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36 Edg/85.0.564.41
[GET] /api/auth/callback/google
15:19:14:02
Status:
302
Duration:
5.69ms
Memory Used:
62 MB
ID:
dc4x6-1609474754021-902653bead5f
User Agent:
Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36
2021-01-01T04:19:14.153Z    e1ad9526-d2f5-4a48-8f2c-8c98fd8a7f87    ERROR   [next-auth][error][callback_oauth_error] Error: Invalid state returned from oAuth provider
    at /var/task/bdevg/node_modules/next-auth/dist/server/lib/oauth/callback.js:46:27
    at Generator.next (<anonymous>)
    at asyncGeneratorStep (/var/task/bdevg/node_modules/next-auth/dist/server/lib/oauth/callback.js:26:103)
    at _next (/var/task/bdevg/node_modules/next-auth/dist/server/lib/oauth/callback.js:28:194)
    at /var/task/bdevg/node_modules/next-auth/dist/server/lib/oauth/callback.js:28:364
    at new Promise (<anonymous>)
    at /var/task/bdevg/node_modules/next-auth/dist/server/lib/oauth/callback.js:28:97
    at /var/task/bdevg/node_modules/next-auth/dist/server/lib/oauth/callback.js:143:17
    at /var/task/bdevg/node_modules/next-auth/dist/server/routes/callback.js:58:31
    at Generator.next (<anonymous>) 
https://next-auth.js.org/errors#callback_oauth_error
[GET] /api/auth/error?error=oAuthCallback
15:19:13:81
Status:
200
Duration:
3.83ms
Memory Used:
62 MB
ID:
46tlr-1609474753656-842d690ca3e2
User Agent:
Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36
[GET] /api/auth/error?error=oAuthCallback
15:19:13:44
Status:
200
Duration:
46.42ms
Memory Used:
62 MB
ID:
p6rrr-1609474753295-3caf0ab0a8c3
User Agent:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36
[GET] /api/auth/callback/google
15:19:12:60
Status:
302
Duration:
47.13ms
Memory Used:
120 MB
ID:
p6rrr-1609474752350-528a3121442e
User Agent:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36
2021-01-01T04:19:12.731Z    f5774683-208d-49fb-b8d7-46a852e6fdda    ERROR   [next-auth][error][callback_oauth_error] Error: Invalid state returned from oAuth provider
    at /var/task/bdevg/node_modules/next-auth/dist/server/lib/oauth/callback.js:46:27
    at Generator.next (<anonymous>)
    at asyncGeneratorStep (/var/task/bdevg/node_modules/next-auth/dist/server/lib/oauth/callback.js:26:103)
    at _next (/var/task/bdevg/node_modules/next-auth/dist/server/lib/oauth/callback.js:28:194)
    at /var/task/bdevg/node_modules/next-auth/dist/server/lib/oauth/callback.js:28:364
    at new Promise (<anonymous>)
    at /var/task/bdevg/node_modules/next-auth/dist/server/lib/oauth/callback.js:28:97
    at /var/task/bdevg/node_modules/next-auth/dist/server/lib/oauth/callback.js:143:17
    at /var/task/bdevg/node_modules/next-auth/dist/server/routes/callback.js:58:31
    at Generator.next (<anonymous>) 
https://next-auth.js.org/errors#callback_oauth_error
[POST] /api/auth/signin/google
15:15:27:33
Status:
302
Duration:
1440.54ms
Memory Used:
119 MB
ID:
dc4x6-1609474527333-0021bfe4f74f
User Agent:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36
Loaded env from .env.production
[POST] /api/auth/signin/google
15:15:26:82
Status:
302
Duration:
1458.67ms
Memory Used:
118 MB
ID:
dc4x6-1609474526822-bef9b75a6e5c
User Agent:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36
Loaded env from .env.production
OlliePrentice commented 3 years ago

I’m getting the same issue on my application when pairing with mongodb. I’ve opened up the IP access, by adding 0.0.0.0/0 but it doesn’t seem to work. Returns 502 after a 10 second timeout.

balazsorban44 commented 3 years ago

Could you please provide some source code? (Ideally a link to a reproduction repository)

bkalafat commented 3 years ago

I have same issue with mail auth too. How should I set database url
prod url looks like this and not working and getting below error

database: process.env.DATABASE_URL

DATABASE_URL=mongodb+srv://dba:*********@cluster0-yaruk.mongodb.net/nextauth

Error: 502: BAD_GATEWAY Code: NO_RESPONSE_FROM_FUNCTION

PS: My mongo db has access from anywhere 0.0.0.0/0

ats1999 commented 3 years ago

Could you please provide some source code? (Ideally a link to a reproduction repository)

NEXTAUTH_URL from vercel dashboard

Screenshot (516)





Github URL's

Screenshot (515)

Code

import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'

// For more information on each option (and a full list of options) go to
// https://next-auth.js.org/configuration/options
const options = {
  // https://next-auth.js.org/configuration/providers
  providers: [
    Providers.GitHub({
      clientId: "13333223131.........",
      clientSecret: "13132133........."
    }),
    Providers.Google({
      clientId: "123123...........",
      clientSecret: "123123.........."
    })
  ],
  // Database optional. MySQL, Maria DB, Postgres and MongoDB are supported.
  // https://next-auth.js.org/configuration/database
  //
  // Notes:
  // * You must to install an appropriate node_module for your database
  // * The Email provider requires a database (OAuth providers do not)
  database: process.env.MONGO_URI,

  // The secret should be set to a reasonably long random string.
  // It is used to sign cookies and to sign and encrypt JSON Web Tokens, unless
  // a seperate secret is defined explicitly for encrypting the JWT.
  secret: process.env.SECRET,

  session: {
    // Use JSON Web Tokens for session instead of database sessions.
    // This option can be used with or without a database for users/accounts.
    // Note: `jwt` is automatically set to `true` if no database is specified.
    jwt: true, 

    // Seconds - How long until an idle session expires and is no longer valid.
    // maxAge: 30 * 24 * 60 * 60, // 30 days

    // Seconds - Throttle how frequently to write to database to extend a session.
    // Use it to limit write operations. Set to 0 to always update the database.
    // Note: This option is ignored if using JSON Web Tokens 
    // updateAge: 24 * 60 * 60, // 24 hours
  },

  // JSON Web tokens are only used for sessions if the `jwt: true` session
  // option is set - or by default if no database is specified.
  // https://next-auth.js.org/configuration/options#jwt
  jwt: {
    // A secret to use for key generation (you should set this explicitly)
    // secret: 'INp8IvdIyeMcoGAgFGoA61DdBglwwSqnXJZkgz8PSnw', 

    // Set to true to use encryption (default: false)
    // encryption: true,

    // You can define your own encode/decode functions for signing and encryption
    // if you want to override the default behaviour.
    // encode: async ({ secret, token, maxAge }) => {},
    // decode: async ({ secret, token, maxAge }) => {},
  },

  // You can define custom pages to override the built-in pages.
  // The routes shown here are the default URLs that will be used when a custom
  // pages is not specified for that route.
  // https://next-auth.js.org/configuration/pages
  pages: {
    // signIn: '/api/auth/signin',  // Displays signin buttons
    // signOut: '/api/auth/signout', // Displays form with sign out button
    // error: '/api/auth/error', // Error code passed in query string as ?error=
    // verifyRequest: '/api/auth/verify-request', // Used for check email page
    // newUser: null // If set, new users will be directed here on first sign in
  },

  // Callbacks are asynchronous functions you can use to control what happens
  // when an action is performed.
  // https://next-auth.js.org/configuration/callbacks 
  callbacks: { 
    // signIn: async (user, account, profile) => { return Promise.resolve(true) },
    // redirect: async (url, baseUrl) => { return Promise.resolve(baseUrl) },
    // session: async (session, user) => { return Promise.resolve(session) },
    // jwt: async (token, user, account, profile, isNewUser) => { return Promise.resolve(token) }
  },

  // Events are useful for logging
  // https://next-auth.js.org/configuration/events
  events: { },

  // Enable debug messages in the console if you are having problems
  debug: false,
}

export default (req, res) => NextAuth(req, res, options)

Explanation

This time, i directly pasted my id and secret into code, It is still not working.

But, the strange is that it is working fine on localhost when i provide the http://localhost:3000 as url.

ats1999 commented 3 years ago

Client code

import {signIn} from "next-auth/client";

// uses
<a href="/api/auth/signin"
                onClick={(e)=>{
                  e.preventDefault();
                  signIn();
                }}
              >Oauth</a>

You can see this link in the footer

balazsorban44 commented 3 years ago

The authorization callback URL should be

https://bdevg.com/api/auth/callback/github

See: https://next-auth.js.org/getting-started/rest-api#get-apiauthcallbackprovider

bkalafat commented 3 years ago

I found the solution like

1) npm install typeorm --save 2) npm install reflect-metadata --save 3) npm i typeorm@0.2.28 4)// _app.ts or _app.js import "reflect-metadata"; ...

ats1999 commented 3 years ago

I found the solution like

  1. npm install typeorm --save
  2. npm install reflect-metadata --save
  3. npm i typeorm@0.2.28 4)// _app.ts or _app.js import "reflect-metadata"; ...

What is this?

bkalafat commented 3 years ago

I found the solution like

  1. npm install typeorm --save
  2. npm install reflect-metadata --save
  3. npm i typeorm@0.2.28 4)// _app.ts or _app.js import "reflect-metadata"; ...

What is this?

If you have issue on production but localhost. this should work for you. Do not forget to add import _app.js then try. It should work.

balazsorban44 commented 3 years ago

502 bad gateway NO_RESPONSE_FROM_FUNCTION suggests that the provider does not get an answer from your application. Possibly because you configured the callback url wrong. The handler callback that will respond to the provider is at

/api/auth/callback/:provider

Please see my previous answer.

ats1999 commented 3 years ago

I changed Authorization callback URL in my GitHub developer setting to https://bdevg.com/api/auth/callback/github, but still I'm getting the same error.

balazsorban44 commented 3 years ago

Hmm, sorry 😕.

"Invalid​ ​state​ ​returned​ ​from​ ​oAuth​ ​provider"

Could you try setting state: false?

https://next-auth.js.org/configuration/providers#oauth-provider-options

ats1999 commented 3 years ago

okey! I'm trying>

ats1999 commented 3 years ago

Could you try setting state: false?

This didn't worked, it takes me http://localhost:3000/api/auth/signin/github after clicking on signin with github or google

when i remove, this then it was working as before.

balazsorban44 commented 3 years ago

do you have a link to your repo?

ats1999 commented 3 years ago

do you have a link to your repo?

It's private

ats1999 commented 3 years ago

OKey: So, i forked your github repo, then i deployed it on https://next-auth-example-iota.vercel.app/

Repo: https://github.com/ats1999/next-auth-example/tree/main/pages

Homepage URL https://next-auth-example-iota.vercel.app Authorization callback URL https://next-auth-example-iota.vercel.app/api/auth/callback/github Now, tell me what should i edit.

This time, I haven't provided NEXTAUTH_URL , because it's looking like optional, https://next-auth.js.org/getting-started/rest-api#get-apiauthproviders

OlliePrentice commented 3 years ago

I have looked more into this issue.

I set up an AWS RDS database to test my application. Everything works correctly in production when doing this. So this means the problem must be to do with how NextAuth is connecting to MongoDB Atlas in production.

MongoDB and NextAuth are working correctly in local development.

I have the network access set to 0.0.0.0/0.

I have tried @bkalafat solution, but it still throws the 502 error.

I have also been able to connect to the database using the code found in a Vercel tutorial: https://vercel.com/guides/deploying-a-mongodb-powered-api-with-node-and-vercel

So I have to believe the issue is either with NextAuth or MongoDB Atlas is blocking the connection when the site runs on Vercel.

If anyone is able to provide a solution to this it would be greatly appreciated. Thanks.

bkalafat commented 3 years ago

Can you share your masked mongodb connection string

bkalafat commented 3 years ago

Set debug mode to true on your auth options. And be sure typeorm package version is 0.2.28

ats1999 commented 3 years ago

Set debug mode to true on your auth options. And be sure typeorm package version is 0.2.28

This doesn't logged anything on console.

ats1999 commented 3 years ago

In my case, mongodb atlas is correctly working,it is an working application. We can communicate with database, there is no db error.

But, still I'm not getting logged in using oauth.

ats1999 commented 3 years ago

If i was used normal oauth workflow not nextauth.js, then i would have made it earlier.

bkalafat commented 3 years ago

In my case, mongodb atlas is correctly working,it is an working application. We can communicate with database, there is no db error.

But, still I'm not getting logged in using oauth.

you should set dbname as /nextauth

ats1999 commented 3 years ago

nextauth or /nextauth?

bkalafat commented 3 years ago

nextauth or /nextauth?

Mine which is working like this for mongodb DATABASE_URL=mongodb+srv://d:**@cluster0-yaruk.mongodb.net/nextauth?retryWrites=true&w=majority

ats1999 commented 3 years ago

Did you tried DATABASE_URL=mongodb+srv://d:**@cluster0-yaruk.mongodb.net/anything?retryWrites=true&w=majority

Because my DB name is bdevg

bkalafat commented 3 years ago

no i am using another db for my application but you should use nextauth for next-auth db name on mongo. I guess its standart for them. Try to add new url path with this /nextauth?.. env file and use that on your next auth options

I Have two different path one is for my application another is for my next-auth

ats1999 commented 3 years ago

ok

bkalafat commented 3 years ago

and you dont have to create db at mongo. Next will generate it automatically

ats1999 commented 3 years ago

yeah

ats1999 commented 3 years ago

URL's in my Github account

Screenshot (517)

Now, i created the DATABASE_URL as you said. There is debug mode is set to true. But, still, there is no improvement. Also, anything is not getting logged on the console.

ats1999 commented 3 years ago

GitHub repo https://github.com/ats1999/next-auth-example working URL https://next-auth-example-iota.vercel.app/

if debug: true, then at least it should log error on console.

See, my repo for more information.

bkalafat commented 3 years ago

i cannot see node modules which I advise you to add.

npm install typeorm --save npm install reflect-metadata --save npm i typeorm@0.2.28 4)// _app.ts or _app.js import "reflect-metadata";

ats1999 commented 3 years ago

npm install typeorm --save npm i typeorm@0.2.28

which version I have to install, latest or 0.2.28?

ats1999 commented 3 years ago

Unpacked Size of typeorm is 17 MB

Why this large-sized module is required? It should not have these kinds of dependency, which force users to bring changes in the existing application. It also increases the bundle size of the application.

ats1999 commented 3 years ago

i cannot see node modules which I advise you to add.

npm install typeorm --save npm install reflect-metadata --save npm i typeorm@0.2.28 4)// _app.ts or _app.js import "reflect-metadata";

I update the repo as you advised, but no improvement. See https://next-auth-example-iota.vercel.app/

bkalafat commented 3 years ago

npm install typeorm --save npm i typeorm@0.2.28

which version I have to install, latest or 0.2.28?

0.2.28

I checked your repo. 0.2.29 is not working you should change it to .28

ats1999 commented 3 years ago

npm install typeorm --save npm i typeorm@0.2.28 which version I have to install, latest or 0.2.28?

0.2.28

I checked your repo. 0.2.29 is not working you should change it to .28

Still, it has the same issue 😂

OlliePrentice commented 3 years ago

Yes I have tried the many different fixes to no avail.

@bkalafat how do you have your MongoDB Atlas configured?

What cluster tier/region are you using?

I have my Network access set to.

Screenshot 2021-01-06 at 10 35 53

Database user role set to Atlas admin.

Connection string works locally, but doesn't work when deployed on Vercel.

mongodb+srv://pr****:**@marquee.jiqul.mongodb.net/nextauth?retryWrites=true&w=majority

Thanks,

Ollie

ats1999 commented 3 years ago

string

Why don't you leave DB configuration on the user? It has already taken, so much time.

ats1999 commented 3 years ago

@balazsorban44 But, it's working here https://next-auth-example.now.sh/ how??

balazsorban44 commented 3 years ago

@iaincollins just reverted some changes on the example app, Iain maybe you could give an answer to this?

flosrn commented 3 years ago

I am facing the same problem with google provider and github provider, only works in dev mode, tried many solutions, stuck for 2 days on this error..

flosrn commented 3 years ago

I'm sure the problem come from the database in [...nextauth].tsx call. I tried many configuration (all) from this https://github.com/nextauthjs/next-auth/issues/833 And the only solution who work for my for not having the MongoServerSelectionError: getaddrinfo ENOTFOUND error is to set database not like this : database: process.env.DATABASE_URL, but like this :

database: {
    type: "mongodb",
    uri: process.env.DATABASE_URL,
    w: "majority",
    useNewUrlParser: true,
    useUnifiedTopology: true,
    retryWrites: true,
  },

(who the DTABASE_URL is mongodb+srv://[username]>:[password]@strapidbcluster.jdadp.mongodb.net/strapi-db)

My configuration for github auth (work perfectly with http://localhost:3000) :

Capture d’écran 2021-01-08 à 14 09 58

My configuration for google auth (work perfectly with http://localhost:3000) :

Capture d’écran 2021-01-08 à 15 11 23

The correct connexion to my backend server and mongo db (handle with strapi) in local dev Capture d’écran 2021-01-08 à 14 12 43

And in production, always after I tried google or github auth (after clicking on my account) i face the same result:

Capture d’écran 2021-01-08 à 14 13 57

0 logs, only this message in my vercel function log:

Capture d’écran 2021-01-08 à 14 21 15

I don't know what else to try 😭

My repo just in case : https://github.com/Flosrn/nextjs-headless-cms

bkalafat commented 3 years ago

I'm sure the problem come from the database in [...nextauth].tsx call.

I tried many configuration (all) from this https://github.com/nextauthjs/next-auth/issues/833

And the only solution who work for my for not having the MongoServerSelectionError: getaddrinfo ENOTFOUND error is to set database not like this :

database: process.env.DATABASE_URL,

but like this :


database: {

    type: "mongodb",

    uri: process.env.DATABASE_URL,

    w: "majority",

    useNewUrlParser: true,

    useUnifiedTopology: true,

    retryWrites: true,

  },

(who the DTABASE_URL is mongodb+srv://[username]>:[password]@strapidbcluster.jdadp.mongodb.net/strapi-db)

My configuration for github auth (work perfectly with http://localhost:3000) :

Capture d’écran 2021-01-08 à 14 09 58

My configuration for google auth (work perfectly with http://localhost:3000) :

Capture d’écran 2021-01-08 à 15 11 23

The correct connexion to my backend server and mongo db (handle with strapi) in local dev

Capture d’écran 2021-01-08 à 14 12 43

And in production, always after I tried google or github auth (after clicking on my account) i face the same result:

Capture d’écran 2021-01-08 à 14 13 57

0 logs, only this message in my vercel function log:

Capture d’écran 2021-01-08 à 14 21 15

I don't know what else to try 😭

My repo just in case : https://github.com/Flosrn/nextjs-headless-cms

wrong db name

OlliePrentice commented 3 years ago

@Flosrn

I think I've finally got it working, try changing 'uri' to 'url'

In package.json add:

"resolutions": { "typeorm": "0.2.28" }

I've tested without the 'reflect-metadata' package and it also works.

Hope this helps everyone.

stale[bot] commented 3 years ago

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 it open. (Read more at #912) Thanks!

stale[bot] commented 3 years ago

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!

biapar commented 2 weeks ago

I've the same problem on Azure. The problem is the NEXTAUTH variabile. I put in the env.production but the server don't read it. So, I solved to put the NEXTAUTH_URL into the Azure App service environment variables. It use the base domain without that variable.