Make external API call in Auth0 NextJS callback before sign in

Viewed 36

I have the following code using @auth0/nextjs-auth0 package. This works well, as written here, logging the user in and then setting the jwt token in cookie.

import { handleAuth, handleLogout, handleCallback } from "@auth0/nextjs-auth0";
import { setCookie, deleteCookie } from "cookies-next";

const afterCallback = (req, res, session, state) => {
  setCookie("auth0token", session.idToken, {
    req,
    res,
    path: "/",
    maxAge: 60 * 6 * 24,
  });

  return session;
};

export default handleAuth({
  async callback(req, res) {
    try {
      await handleCallback(req, res, { afterCallback });
    } catch (error) {
      res.status(error.status || 500).end(error.message);
    }
  },
  async logout(req, res) {
    deleteCookie("auth0token", { req, res, path: "/" });

    await handleLogout(req, res);
  },
});

However, I need to fetch data about the user from an external service before logging the user in. If they are not found, I want to throw an error and deny authentication. This code below I've tried results in error checks.state argument is missing - what is the best practice for executing API requests before authenticating?

import { handleAuth, handleLogout, handleCallback } from "@auth0/nextjs-auth0";
import { setCookie, deleteCookie } from "cookies-next";

const afterCallback = (req, res, session, state) => {
  const options = {
    method: "GET",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
  };

  fetch(
    `https://myapi.com/api/get-user-details/?user_email=${session.user.email}`,
    options
  )
    .then((response) => response.json())
    .then((response) => {
      if (response.status === 200) {
        setCookie("auth0token", session.idToken, {
          req,
          res,
          path: "/",
          maxAge: 60 * 6 * 24,
        });

        return session;
      } else {
        res.status(error.status || 500).end(err.message);
      }
    })
    .catch((err) => {
      res.status(err.status || 500).end(err.message);
    });
};

export default handleAuth({
  async callback(req, res) {
    try {
      await handleCallback(req, res, { afterCallback });
    } catch (error) {
      res.status(error.status || 500).end(error.message);
    }
  },
  async logout(req, res) {
    deleteCookie("auth0token", { req, res, path: "/" });

    await handleLogout(req, res);
  },
});
1 Answers

I think you have to set httpOnly to false. default is true. So the cookie cannot be accessed through the client-side script. That is why you get "state is missing` means that no access to the cookie.

Related