next-auth: Why occurs 'OAuthCallback' error only in production? - next.js

I want add signin features using 'GoogleProvider' in next-auth.
I finished google cloud and firebase settings
OAuth 2.0 client ID in Credentials
App domain, Authorized domains in OAuth consent screen
create web app in firebase project settings
and [...nextauth].ts code is below:
import NextAuth, { NextAuthOptions } from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import KakaoProvider from "next-auth/providers/kakao"
import { FirestoreAdapter } from "#next-auth/firebase-adapter";
import { db } from "../../../firebase.config";
const authOptions: NextAuthOptions = {
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID_DEV as string,
clientSecret: process.env.GOOGLE_CLIENT_SECRET_DEV as string
})
],
secret: process.env.NEXTAUTH_SECRET,
session: {
strategy: "jwt",
maxAge: 3 * 60 * 60
},
adapter: FirestoreAdapter(db.app.options),
pages: {
signIn: '/login'
},
callbacks: {
async session({ session, user, token }) {
return session;
}
},
debug: true
}
export default NextAuth(authOptions);
This project is deploying with Github Actions, Cloud Run, Firebase Hosting.
It works very well in local but not works in production.
Interestingly, It works well in Cloud Run project service URL.
Only not works in domain web page that used Firebase Hosting.
so, I tried these
change Authorized redirect URIs in OAuth 2.0 client ID
Edit app registration in OAuth consent screen
callbackUrl property in signIn function
Is this problem caused by Firebase Hosting?
How can I solve this problem?
Thanks.
+add
When I was looking log in Cloud Run, I found these logs:
https://next-auth.js.org/errors#oauth_callback_error checks.state argument is missing.
error: TypeError: checks.state argument is missing.
name: 'OAuthCallbackError'

Related

Next js - Next Auth - Keep having error=OAuthCreateAccount (google provider)

I have set up next-auth with the GoogleProvider.
Everything works fine locally, however in production, I am having aOAuthCreateAccount error: api/auth/signin?error=OAuthCreateAccount
stating "Try signing in with a different account."
I have provided the ID & Secret of the Provider, I have dropped my DB, tried to log with multiples accounts... I do not understand. Is there something that my production environment is not accessing?
Here's my nextauth.js:
`
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import CredentialsProvider from "next-auth/providers/credentials";
import { MongoDBAdapter } from "#next-auth/mongodb-adapter";
import clientPromise from "../../../lib/mongodb";
export default NextAuth({
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
// ...add more providers here
],
secret: process.env.NEXTAUTH_SECRET,
// Can custom page & path
pages: {
signOut: "/auth/signout",
error: "/auth/error", // Error code passed in query string as ?error=
verifyRequest: "/auth/verify-request", // (used for check email message)
// newUser: "/auth/new-user", // New users will be directed here on first sign in (leave the property out if not of interest)
newUser: "/recruiter/2", // New users will be directed here on first sign in (leave the property out if not of interest)
},
adapter: MongoDBAdapter(clientPromise),
});
`
And my mongodb.js:
`
import { MongoClient } from "mongodb";
const uri = process.env.MONGODB_URI;
const options = {
useUnifiedTopology: true,
useNewUrlParser: true,
};
let client;
let clientPromise;
if (!process.env.MONGODB_URI) {
throw new Error("Please add your Mongo URI to .env.local");
}
if (process.env.NODE_ENV === "development") {
// In development mode, use a global variable so that the value
// is preserved across module reloads caused by HMR (Hot Module Replacement).
if (!global._mongoClientPromise) {
client = new MongoClient(uri, options);
global._mongoClientPromise = client.connect();
}
clientPromise = global._mongoClientPromise;
} else {
// In production mode, it's best to not use a global variable.
client = new MongoClient(uri, options);
clientPromise = client.connect();
}
// Export a module-scoped MongoClient promise. By doing this in a
// separate module, the client can be shared across functions.
export default clientPromise;
`
Thank you!
Read the documentations.
Look on Stackoverflow and github thread, tried all the offered solutions, in vain.
I have managed to fix it reading this thorough article: https://medium.com/geekculture/why-and-how-to-get-started-with-next-auth-61740558b45b
I was missing the database variable in my deployment system (vercel) :)

Unexpected behaviour of logging errors in console using Next-Auth

I am making a Next.js app with Next-auth.js authentication. The app is deployed on vercel. When I tried to open my app, it shows error in console. Here is the list of errors:
Failed to load resource: the server responded with a status of 500 ()
[next-auth][error][CLIENT_FETCH_ERROR]
https://next-auth.js.org/errors#client_fetch_error There is a problem with the server configuration. Check the server logs for more information.
/api/auth/_log:1 Failed to load resource: the server responded with a status of 500 ()
it could be that you forgot 'secret' option in your [...nextauth].js. It seems to be mandatory since v4 in Prod.
https://next-auth.js.org/getting-started/upgrade-v4#missing-secret
I recently migrated some projects to NextAuth v4.14
import NextAuth from "next-auth"
import GithubProvider from "next-auth/providers/github"
import GoogleProvider from "next-auth/providers/google";
export const authOptions = {
// Configure one or more authentication providers
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
})
// ...add more providers here
],
secret: process.env.SECRET
}
export default NextAuth(authOptions)

Next Auth doesn't work with custom basePath

My NextAuth are returning 404 when searching for api/auth/session at credential provider custom login, seems like Next Auth are pointing to the wrong url.
My next.config.js have a basePath that points to a subfolder basePath: '/twenty-test' and my NEXTAUTH_URL is already set to my subdomain,
but when I go to my credential provider login custom page (that was working at localhost because it was not at a subdomain), i see an 404 error at console like https://explample.com/api/auth/session 404.
This is my custom provider config:
providers: [
CredentialProvider({
name: 'Credentials',
type: 'credentials',
async authorize(credentials) {
//
if(credentials.email == "john#gmail.com" && credentials.password == "test"){
return {
id: 2,
name: 'John Doe',
email: 'john#gmail.com',
permition: {
group: 2,
level: 0
}
}
}
return null;
}
})
],
This is my next.config.js
const nextConfig = {
reactStrictMode: true,
basePath: '/twenty-test',
images: {
domains: ['example.com'],
},
}
module.exports = nextConfig
This is my NEXTAUTH_URL env variable
NEXTAUTH_URL="https://example.com/twenty-test/api/auth"
This is my getCsrfToken config
export async function getServerSideProps(context) {
return {
props: {
csrfToken: await getCsrfToken(context)
}
}
}
My project are not on vercel. I'm using a custom server config to deploy with cPanel
The problem was on building the app in localhost and deploying on server.
The app was building expecting NEXTAUTH_URL as localhost, and simply changing the .env variable on server didnt worked.
The solution was building the app on server.
Another workaround was replacing the localhost NEXTAUTH_URL ocurrences after building with the value of NEXTAUTH_URL on server.

Firebase Auth Import SHA256 Hash: Can't login with password after import

I'm trying to migrate users (using firebase-admin#8.13.0) into firebase auth, following this guide:
https://firebase.google.com/docs/auth/admin/import-users#import_users_with_md5_sha_and_pbkdf_hashed_passwords
In the old system, the passwords were hashed in php:
$Password = hash('sha256', $Password);
I'm running this code to import the users into firebase:
const res = await admin.auth().importUsers([{
uid: 'ABC123',
email: 'tester#test.com',
passwordHash: Buffer.from('5457ae6b180556bc65b423ba3a36124ec44f6cbec7da84e483daa2a46dec3f97')
}], {
hash: {
algorithm: 'SHA256',
rounds: 1
}
});
The import succeeds, but I can't login using the same password (LeeT1337).
Also when I export all users, running
firebase auth:export auth-export.json --format json
the imported user, unlike all others, doesn't have a passwordHash property.
I've also tried base64-encoding the hash first (since it's suggested in old stack posts, but not in the docs anymore).
Alternativlely I've tried importing via the cli (firebase-tools#8.13.1) with:
{
"users": [
{
"localId": "ABC123",
"email": "tester#test.com",
"passwordHash": "NTQ1N2FlNmIxODA1NTZiYzY1YjQyM2JhM2EzNjEyNGVjNDRmNmNiZWM3ZGE4NGU0ODNkYWEyYTQ2ZGVjM2Y5Nw=="
}
]
}
and
firebase auth:import users-for-import.json --hash-algo=SHA256 --rounds=1
but got the same result: Import works, login doesn't.
Buffer.from('5457ae6b180556bc65b423ba3a36124ec44f6cbec7da84e483daa2a46dec3f97')
needs to be changed to
Buffer.from('5457ae6b180556bc65b423ba3a36124ec44f6cbec7da84e483daa2a46dec3f97', 'hex')

Meteor loading Firebase Admin on Server Side

I am working on a React Native / Meteor combo, Where Meteor is my server. I need to set up a Firebase admin instance to send an API request for triggering push notifications for my React Native app.
I have installed the Firebase NPM SDK, when I go to import and/or require the firebase.admin object instance is empty or incomplete. Works fine if I load it into a normal node app setup.
I am assuming there is a latency with the import/require. I looked at some wrapper packages but they are outdated and unmaintained.
import * as admin from 'firebase-admin'
console.log(admin)
Should print
FirebaseNamespace {
__esModule: true,
credential:
{ cert: [Function: cert],
refreshToken: [Function: refreshToken],
applicationDefault: [Function: applicationDefault] },
SDK_VERSION: '6.2.0',
Promise: [Function: Promise],
INTERNAL:
FirebaseNamespaceInternals {
firebase_: [Circular],
serviceFactories: {},
apps_: {},
appHooks_: {} },
default: [Circular] }
But instead prints
{ default: {}, [Symbol(__esModule)]: true }

Resources