Search code examples
reactjsamazon-web-servicesamazon-cognitonext-authnextjs14

Getting invalid_client error using next-auth for cognito


I have a Next JS app, a next-auth library and aws cognito to store user information. I created a public client in my Cognito userpool and using that userpool id & client id, I initially successfully connected my application to Cognito. Back then, I was not using next-auth.

Now I decided to use next-auth and take all this server side. I'm still using the old cognito client. It properly redirects me to Cognito login UI, but after a successful login, the following error is triggered by next-auth

https://next-auth.js.org/errors#oauth_callback_error invalid_client {
  error: OPError: invalid_client ...

Then there is a trace of the error followed by

  name: 'OAuthCallbackError',
    code: undefined
  },
  providerId: 'cognito',
  message: 'invalid_client'
}

Why am I getting this error?

Given Next JS link states that 'OAUTH_CALLBACK_ERROR' signifies

This can occur during the handling of the callback if the code_verifier cookie was not found or an invalid state was returned from the OAuth provider.

I'm not sure what this 'code_verifier' cookie is, since I didn't try to do anything advanced with next-auth, I haven't altered any configuration that would trigger this.


Solution

  • next-auth will run it in the server side, which is why you would need a Confidential client instead of a Public client.

    This is how AWS Cognito described different type of clients -

    Public client: A native, browser or mobile-device app. Cognito API requests are made from user systems that are not trusted with a client secret.

    Confidential client A server-side application that can securely store a client secret. Cognito API requests are made from a central server.

    Different type of Cognito client (from their console)

    Which is why although your previous public client was working non-server side, this client is 'invalid' to be used in a server-side functionality provider like next-auth.

    Create a Confidential client and make use of the client secret.