Moving Forward with Next Auth for Secure OAuth Integration

My app was working fine until today when I encountered an error while trying to log in with Google using NextAuth. The error message I received is shown in the screenshots below:

https://i.sstatic.net/FFTKc.png

https://i.sstatic.net/juZko.png

The terminal output for this issue is as follows:

https://i.sstatic.net/9TS5v.png

I have attempted to resolve the problem by changing the client ID and Secret, but the issue persists.

Below is the code snippet from my NextAuth configuration:

const authOptions = {
  providers: [
    // OAuth authentication providers...
    GoogleProvider({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_SECRET,
      authorizationUrl:
      "https://accounts.google.com/o/oauth2/v2/auth?propmt=consent&access_type=offline&response_type=code",
    })
    
  ],
  secret: process.env.NEXTAUTH_SECRET,
  adapter: MongoDBAdapter(clientPromise),
  callbacks: {
    async signIn({ account, profile }) {
      if (account.provider === "google") {
        return profile.email_verified && profile.email.endsWith("@gmail.com")
      }
      return true // Do different verification for other providers that don't have `email_verified`
    },
    session: ({session, token, user}) => {
      if (adminEmails.includes(session?.user?.email)) {
        return session;
      }
      else {
        return false;
      }
    },
  },
}

export default NextAuth(authOptions)

export async function isAdminRequest(req,res) {
  const session = await getServerSession(req,res,authOptions);
  if (!adminEmails.includes(session?.user?.email)) {
    res.status(401);
    res.end();
    throw 'not admin';
  }
}

Answer №1

After some troubleshooting, I was able to figure it out. The issue turned out to be a simple one - I had mistakenly set the ports to 3001 instead of the correct value of 3000 in my settings.

Answer №2

     **To set up NextAuth.js with your OAuth provider, you'll first need to configure it by creating a file at pages/api/auth/[...nextauth].js in your Next.js project. Customize the content of this file according to your provider's specifications.**
    
    import NextAuth from "next-auth"
    import Providers from "next-auth/providers"
    export default NextAuth({
      providers: [
        Providers.ProviderName({
          clientId: process.env.PROVIDER_CLIENT_ID,
          clientSecret: process.env.PROVIDER_CLIENT_SECRET,
        }),
      ],
    })

**Once configured, you can use the NextAuth.js client in your application to handle user sign-ins, session checks, and logouts. For instance, if you want to add a sign-in button:**

import { signIn, signOut, useSession } from "next-auth/client"

export default function Component() {
  const [session, loading] = useSession()
  return (
    <div>
      {!session && (
        <button onClick={() => signIn('providerName')}>Sign in</button>
      )}
      {session && (
        <div>
          <p>Signed in as {session.user.email}</p>
          <button onClick={() => signOut()}>Sign out</button>
        </div>
      )}
    </div>
  )
}

Setting Up Your Application

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transform nested entities into a single entity where any properties that are objects inherit from their parent as prototypes

Exploring a new concept. Consider an object like: T = { a: 2, b: 9, c: { a: 3, d: 6, e: { f: 12 } } } The goal is to modify it so that every value that is an object becomes the same object, with the parent object as prototy ...

Sending Data in Angular JS

Looking for guidance on Angular JS as a newcomer. I have set up a form on my index.html page, and when the user fills in the details and hits submit, I want it to redirect to a details.html page where all the filled-in information can be displayed. HTML ...

Ensure that the Observable is properly declared for the item list

.html // based on the error message, the issue seems to be in the HTML code <ion-card *ngFor="let invitedEvent of invitedEvents"> <ion-card-content> <img [src]="eventPhotoUrl$[invitedEvent.id] | async"> </ion ...

Obtaining Compiled HTML Output Using AngularJS

I'm running into an issue with obtaining the compiled html of a page in AngularJS. Below is the code snippet that demonstrates this problem: JavaScript: <script src="http://code.angularjs.org/1.2.0rc1/angular.min.js"></script> &l ...

having difficulty transmitting parameter to angular directive

After assigning a collection to a source variable, I am trying to activate a third party control (bootstrap-select) using a directive that watches the assigned collection. angular .module('app').directive('bootstrapDropdown', ['$t ...

Ensure that both Vue methods are executed synchronously

I am working with two Vue methods: (1) this.retrieveSavedSearches() (2) this.updateDefaultSelectOption() Is there a way to ensure that method (2) only executes after method(1) has completed its execution? ...

The MaterialUI Datagrid is throwing an error message for an Invalid Hook Call

Having a strange issue with my simple component. I've imported DataGrid from MaterialUI, defined variables for columns and rows, and rendered the DataGrid in a functional component. However, I'm getting an "invalid hook call" error. Most solution ...

I am encountering an error when attempting to import the app from the server.js file in Express

In my server.js file, I have set up an express server and exported the app from it. //server.js require("dotenv").config(); const express = require("express"); const app = express(); const connectToDb = require("./connectToDb ...

Using JavaScript to place markers on a Google Map may encounter an issue with a for

Close to solving a three-day challenge. Currently working on placing markers on a Google Map using latitudes and longitudes stored in a Django model. This is my first time using AJAX, but I'm giving it a shot to make this work. Firebug is pointing out ...

What is the reason for Rich file manager to include filemanager.config.json instead of simply adding an image to the text

I have integrated Rich File Manager with Laravel 5.3.20 using the default configuration provided below: Javascript <script> CKEDITOR.replace( 'textarea', { filebrowserBrowseUrl: '{!! url('gallery/index.html& ...

Issue with accessing Next.js API endpoint in Docker container

My issue is: I recently created a basic web page using Next.js. I fetch some content from /pages/api/ endpoints in JSON format and display it on various pages and components. Building the project locally (npm run dev or npm run start) works perfectly fine ...

Reloading the table columns in a JSP page with a click of the refresh button on every row using AJAX and JavaScript

Hey there! I have a JSP page with a table where data is displayed by iterating through a list from the action class. Each row in the table has a refresh button at row level. Here is a snippet of the JSP: <script type="text/javascript"> functi ...

Display a single video on an HTML page in sequential order

My webpage contains a video tag for playing online videos. Instead of just one, I have utilized two video tags. However, when attempting to play both videos simultaneously, they end up playing at the same time. I am seeking a solution where if I start pla ...

Warning on React component listing due to key issue originating from the parent component

Alert: It is essential that each child in a list has a distinct "key" prop. Please review the render method of ForwardRef(ListItem). A child from RecipientsList was passed. I have located this issue using the react-components debugger tool on Chrome. I ad ...

Can Node.js be utilized to generate an XLS excel file while specifying the cell type?

I've noticed that many libraries have the capability to export to XLSX (Excel > 2007) or CSV formats, but not in XLS (which I assume is due to its outdated file format). I came across something where if you use fs.createOutputStream("filename. ...

Guide on transforming a PHP array encoded in JSON into a JavaScript array

After fetching a JSON encoded array via AJAX from a PHP file, I need to manipulate it as an array in JavaScript. How can I achieve this? Here is my AJAX call to the PHP File: $.ajax({ type:"POST", url:"ajaxfetch.php", success:function(re ...

Encountering an issue with NextJS and mongoose when setting up a login API with bcrypt hashing

I'm in the process of setting up an endpoint that verifies a user's existence and then compares the entered password with the hashed password stored in MongoDB. Utilizing NextJS, Mongoose, and Bcrypt for this task. The user model includes a funct ...

The CSS and Javascript files are failing to load

My web page is not displaying my CSS and JavaScript properly when I access it through a folder in the browser. Both files are located within multiple subfolders. I have attempted to rename the files to troubleshoot the issue. <head> <link rel=" ...

Error encountered in Next.js when defining columns for a MUI data grid

Currently, I am integrating MUI Data Grid into a Next.js app under development. While attempting to define a more intricate column structure, I encountered an error: { field: 'home_address', valueGetter: (value, row) => { retur ...

Picture in a clear background without any alteration

Is there a way to create a background-color with opacity inside an image without affecting the image itself? The issue lies in the fact that the transparent background-color makes everything underneath it, including text and the image, transparent. Below ...