Error occurred during Apple Login using Next_Auth: OAuthCallback issue

Attempting to log in with Apple using NextAuth. Authentication is successful, but it redirects to /?error=OAuthCallback. The URL being used is:

 https://appleid.apple.com/auth/authorize?client_id=com.wheeleasy.org&scope=name%20email&response_type=code&redirect_uri=https%3A%2F%2Fdevelop-sr3snxi-sq2r64cdk53qe.au.platformsh.site%2Fapi%2Fauth%2Fcallback%2Fapple&response_mode=form_post&code_challenge=lelepvmyqyryTiyWL6NthxspYae6t9XYB1PAj3e3c_E&code_challenge_method=S256

enter image description here

This is the code snippet for generating client secret, which was generated successfully.

const { SignJWT } = require("jose");
const fs = require("fs");
const path = require("path");
const { createPrivateKey } = require("crypto");

// Constants for Apple API credentials and key generation
const teamId = process.env.TEAM_ID;
const clientId = process.env.CLIENT_ID;
const keyId = process.env.KEY_ID;
const expiresIn = 86400 * 180;
const privateKeyPath = path.join(__dirname, "AuthKey_CW5NRK3ZSN.p8");
const exp = Math.ceil(Date.now() / 1000) + expiresIn;
const expiresAt = Math.ceil(Date.now() / 1000) + expiresIn;
const expirationTime = exp ?? expiresAt;

let privateKey;
try {
  privateKey = fs.readFileSync(privateKeyPath, "utf8");
  console.log("Private Key Read Successfully");
} catch (err) {
  console.error("Error reading private key:", err);
  process.exit(1);
}

(async () => {
  try {
    const jwt = await new SignJWT({})
      .setAudience("https://appleid.apple.com")
      .setIssuer(teamId)
      .setIssuedAt()
      .setExpirationTime(expirationTime)
      .setSubject(clientId)
      .setProtectedHeader({ alg: "ES256", kid: keyId, typ: "JWT" })
      .sign(createPrivateKey(privateKey));

    console.log("Client Secret:", jwt);
  } catch (err) {
    console.error("Error generating JWT:", err);
  }
})();
import NextAuth from "next-auth/next";
import GoogleProvider from "next-auth/providers/google";
import FacebookProvider from "next-auth/providers/facebook";
import AppleProvider from "next-auth/providers/apple";

export default NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
    FacebookProvider({
      clientId: process.env.FACEBOOK_CLIENT_ID,
      clientSecret: process.env.FACEBOOK_CLIENT_SECRET,
    }),
    AppleProvider({
      clientId: process.env.APPLE_CLIENT_ID,
      clientSecret: process.env.APPLE_CLIENT_SECRET,
    }),
  ],
  callbacks: {
    session: async ({ session, token }) => {
      if (session?.user) {
        session.user.id = token.uid;
      }
      return session;
    },
    jwt: async ({ user, token }) => {
      if (user) {
        token.uid = user.id;
      }
      return token;
    },
  },
  session: {
    strategy: "jwt",
  },
});

I have all the necessary information such as team ID, key ID, and AuthKey file to generate a client secret. While trying to login with Apple, I am being redirected to an error page (/?error=OAuthCallback). I aim to successfully integrate Apple login functionality.

Answer №1

Consider incorporating "redirect=false" within the signIn process to effectively troubleshoot any errors by logging res.error.

Utilizing Redirect = false will ensure that your application does not automatically redirect to the default next.js error page upon encountering a signin issue.

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

Is there a way to make the console output more visually appealing with some styling?

What techniques do programs such as npm and firebase use to generate visually appealing and informative console output during command execution? Consider the following examples: $ firebase deploy or $ npm i <some-package> ...

The "maxlength" attribute does not function with the input type "number" in an HTML textbox

The maxlength attribute does not seem to be functioning properly when using type="number" ...

Leveraging periods within a MySQL database: Node.js for seamless updates

I am currently facing a challenge in updating a column name that contains a period in node using node-mysql. I appreciate the convenience of being able to update multiple columns by providing an object with keys, but the string escaping process with node-m ...

Using JLinq for Date-Based Filtering of JSON Data

I have been trying to use JLinq for filtering JSON data, but I am facing an issue with filtering by date. Despite attempting different methods, the problem persists. Below is a snippet of my code: //This works jlinq.from(myData) .select(function ...

Updating numerous records with varying values

Utilizing jQuery UI's sortable feature (source) allows me to rearrange elements effortlessly. By implementing custom callbacks, I can generate a list of these elements, assigning each a new position ID as I move them around. The resulting list may app ...

Is it possible to create an HTML form to edit XML data?

I'm currently working on developing a JavaScript plugin that will allow users to easily edit XML files. The idea is to take an XML string representing an object, generate an HTML form dynamically for editing the values, and then save the changes back ...

Should tabs be closed or redirected after successful authentication with Google?

I have a project that was developed using perl-dancer and angular. The project is integrated with Google as an openID system. On some of the pages, there is an edit grid with a save button. To prevent loss of unsaved data when the session (created from pe ...

Has xlink:href become outdated for svg <image> elements?

In the realm of SVG attributes, it is noted by MDN xlink:href that href should be used over xlink:href. Interestingly, on the svg example page, last revised on July 6, 2017, the attribute utilized in the given example is xlink:href. The question arises: ...

What is the best way to adjust a CSS width using the output from a JavaScript function?

I am facing a challenge with a GridView within a div wrapper. The row headers along the left side need to always be visible. So far, this setup is working fine. However, I need the wrapper to have a variable width to adjust to the browser size. Although I ...

Reveal concealed content when a responsive table becomes scrollable on a mobile device

I recently completed a project that was overloaded with tables. I made all the tables responsive, but they still take vertical scroll if they don't fit on certain devices due to their varying widths. For instance, Table A requires vertical scroll o ...

The sequence in which functions are executed when bound to an event in JavaScript

Recently, I found myself diving into the world of JavaScript to uncover details about how functions bound to a page event are executed. Take, for instance, when using an EventListener. Let's say you bind three functions - A(), B(), and C() - to the s ...

Utilizing the fetch() method in Vuex to obtain a restful API

Struggling to integrate my API data through Vuex, I am in dire need of a reliable guide or perhaps someone who can assist me with this task. Previously, without using Vuex, all my requests functioned flawlessly. However, now I'm unsure about the neces ...

Although React forms are being detected, the submission is not being recorded

I have been a fan of Netlify forms for quite some time now. However, I am facing an issue while trying to integrate them into my react app for the first time. Although I followed the official guide and the form appears in my dashboard, it doesn't seem ...

Accessing store state in axios plugin with Nuxt.js

I've encountered a problem where I have a token stored, but I'm struggling to access it in my axios plugin while using Nuxt.js. In the past with just Vue, it was simple to import the store and access the token. However, I'm having difficulty ...

Updating JSON objects in jQuery with string keys

I have an array variable containing JSON data and I need to update specific values within the array using string keys. Here is a snippet of what my array looks like: { "all": [ { "image":{ "URL":"img/img1.jpeg", ...

Choosing a specific column in an HTML table using jQuery based on the text within it

I have a table with a similar structure as shown below: <table> <c:forEach ...> <tr> <td>test</td> // this is the initial value <td>random value</td> <td>random value</td&g ...

Utilizing object properties to dynamically update components in VueJS

Are you familiar with dynamically changing a component using object props? App.vue <template> <div id="app"> <component :is="current['test'].target.name"> </component> <input type="bu ...

What is the reason why setting 'onClick' as an event handler is not flagged as a syntax error?

I am currently working on a JavaScript code snippet where I am trying to change the headline text when it is clicked. The code I have written is: var headline = document.getElementById("mainHeading"); headline.onClick = function() { headline.innerHTML ...

JavaScript object merging (let's coin a term)

Is it possible to natively transform an object in JavaScript? { sample:{ name:"joe", age:69 } } into { 'sample.name': 'joe', 'sample.age': 69 } I have tried the following method, and it appears to wor ...

What is the best way to send a string parameter from an Angular UI to a Node.js backend?

My goal is to transfer a string value from an Angular UI to a Node.js backend API, which will then search in MongoDB using the provided string value as shown below. I am attempting to receive input in enteredValue and pass it on to the http.get call as pa ...