Upgrade access token to cookie or enable access token authentication

I am working on a React and Next JS web application with auth0 for session/cookie-based authentication. I need to programmatically invoke an API from another source, but the only credential I have is an access token. I'm considering two potential solutions:

  1. Is there a way to use an access token to generate cookies on the client side in order to make API calls to the web app?
  2. How can I configure the nextjs+react+auth0 web app to accept an access token as a valid credential?

As I have control over both sides of the code, I am open to any suggestions or solutions.

Answer №1

To enhance security measures, it is essential to include an alternative authentication method in your API request. One option is to utilize NextAuth within an API route.

For instance:

import { getServerSession } from 'next-auth/next';
import { authOptions } from '../../auth/[...nextauth]';

export default async function handler(
    req, //: NextApiRequest,
    res  //: NextApiResponse
) {
    const session = await getServerSession(req, res, authOptions);
    
    let user = null;
    if (session) user = session.user;
    else {
        const token = req.headers.get('Authorization').replace(/^Bearer /, '');
        user = await validateToken(token);
        if(!user){ //validate token and generate the user defined by your external caller
            res.status(401).end();
            return;
        }
    }
    // Perform tasks with authenticated user;
    // In relation to requiring a cookie for an upstream server:
    fetch('upsteamurl', {
        headers:{
            'Set-Cookie': makeCookieHeader(req.query.monitor, 'sent', {path:'/', secure:false, sameSite:'strict', httpOnly:false}))
        }
    }).then(... // use the upstream response
    ...
    }
    
function makeCookieHeader(name, value, opts){
    let header = name +'='+value;
    if(opts){

        if (opts.maxAge) opts.expires = new Date(Date.now() + opts.maxAge);

        if (opts.path     ) header += '; path=' + opts.path;
        if (opts.expires  ) header += '; expires=' + opts.expires.toUTCString();
        if (opts.domain   ) header += '; domain=' + opts.domain;
        if (opts.sameSite ) header += '; samesite=' + (opts.sameSite === true ? 'strict' : opts.sameSite.toLowerCase());
        if (opts.secure   ) header += '; secure';
        if (opts.httpOnly ) header += '; httponly';
    }

    return header;

}
    

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

Building Next.js with a designated maximum number of processes/threads

I've uploaded a fresh Next.js app to the cloud server using npx create-next-app. However, when I try to run the build script, the server throws an error 'pthread-create: Resource temporarily unavailable'. { "name": "next&quo ...

Encountered an Issue in Integrating TailwindCSS with NextJS Due to postcss.config.js Issue

I recently made the switch from Vite to NextJS by following the official migration guidelines. However, when I attempted to incorporate tailwindcss into my Next project, I encountered an error similar to what is shown in the image linked below. View the e ...

Error Encountered in NextJS 12: Unexpected ')' Token Causing Runtime Crash

Since the release of NextJS 12, I have been experiencing an issue that is preventing me from upgrading to version 12.0.8. The problem occurs when I make the first request to my application after it builds successfully and starts the server. Unfortunately, ...

I'm curious, can you explain the significance of the 'loading' return value in useSession() when using next-auth?

I'm currently working on a React project with authentication features using Google and react-auth. While going through the documentation for react-auth, I noticed a function called useAuth() that returns two values: user and loading. Strangely enough, ...

Next.js in combination with Tailwind CSS

While attempting to customize the styling for my Next.js 13 app, I encountered an error message that states: Syntax error: C:\Users\User\Documents\webdev\TicketingApp\ticketing-app\app\globals.css The text-default- ...

Inquiry on SSGHelpers and GetStaticProps functionality with parameterization

I am currently implementing createProxySSGHelpers to prefetch data using trpc in a project I'm developing, but I'm facing an issue where the id from the url params is returning as undefined even though it's visible in the url bar. Below is ...

Retrieve information from multiple RSS feeds using Next.js

As a newcomer to Next.js, I decided to experiment with a newsfeed tool to get more acquainted with the framework. My goal was to retrieve data from a collection of RSS feeds, but I encountered some unexpected issues in the process. How should I proceed? B ...

When accessing my website through a hyperlink, NextJS displays that I am logged out

On the top right corner of my website, there is a user bar component that displays my username if I am logged in, or shows a "Sign In" link. However, every time I land on my website from an external site, it only shows the "Sign In" link instead of recogn ...

Serverless-framework in conjunction with Next.js Lambda function surpasses the allotted size limit for unpacked files

Seeking guidance on reducing the package size of a ssr application (next.js & serverless-framework) to meet AWS's 250MB limit: An error occurred: ServerLambdaFunction - Unzipped size must be smaller than 262144000 bytes (Service: AWSLambdaInternal; St ...

When there is an error or no matching HTTP method, Next.js API routes will provide a default response

Currently, I am diving into the world of API Routes in Next.js where each path is structured like this: import { NextApiRequest, NextApiResponse } from "next"; export default async (req: NextApiRequest, res: NextApiResponse) => { const { qu ...

Low scoring performance in Lighthouse on a nearly empty page built with Next.js

While working on my Next.js project locally, I used npm run dev for development. After testing my website, I noticed that it scored a 40 in Performance. https://i.stack.imgur.com/3jmro.png Despite trying to use Lighthouse in secret mode, the results rem ...

"Encountered an error of 'Authentication failed' while trying to access a blob using the SAS

My team and I are currently in the process of developing a NextJS web app, and we have recently integrated Azure Blob Storage for file upload and display. I am tasked with working on displaying images on the frontend. To achieve this, I am using the genera ...

Is there a way to sort search outcomes by a drop-down menu in Next.js?

I am currently working on implementing a filter for my data based on selections made in a drop-down menu. Here's the setup: I have MSSQL data being pulled into NextJS using Prisma (ORM). My goal is to create a dropdown filter that will refine the di ...

Oops! An issue occurred at ./node_modules/web3-eth-contract/node_modules/web3-providers-http/lib/index.js:26:0 where a module cannot be located. The module in question is 'http'

I have been troubleshooting an issue with Next.js The error I am encountering => error - ./node_modules/web3-eth-contract/node_modules/web3-providers-http/lib/index.js:26:0 Module not found: Can't resolve 'http' Import trace for req ...

Can you explain the process of accessing data from [[PromiseValue]] while utilizing React hooks?

My current challenge involves fetching data from an API and utilizing it in various components through the Context API. The issue arises when I receive a response, but it's wrapped under a Promise.[[PromiseValue]]. How can I properly fetch this data ...

Exploring the capabilities of the Next.js framework with the powerful Advanced Custom Fields Repeater

Having trouble implementing an ACF repeater field in my Next.js project. I have a block with a repeater field containing sub fields, and although I can retrieve the data, I'm unsure how to iterate through it. Below is a snippet of my JavaScript file: ...

Challenge with the revalidateTag() function in Next.js app routing and Sanity integration

I have been struggling to integrate the next app router with Sanity and revalidateTag() function. It has been a challenging journey as I tried to make it work for five full days across multiple projects. Here is what I have discovered so far: Project 1: T ...

Issue: React child must be a valid object - Runtime Error Detected

As I delve into the world of React, NextJs, and TypeScript, I stumbled upon a tutorial on creating a navbar inspired by the 'Strip' style menu. It has been quite a learning journey for me as a newbie in these technologies. After seeking help for ...

Missing data list entries for next js server actions

After successfully running my add function, I noticed that the data I added earlier is not being reflected in the list when I check. import React, { useEffect, useState } from "react"; import { createPost } from "./actions"; import { SubmitButton } from ". ...

Next.js is reporting an error where the Schema has not been registered for Mongoose

Recently, I started using next.js and encountered an issue when calling an API with a reference to another document. Mongoose threw an error saying "Schema hasn't been registered for model". Below is the code snippet: Models Task.js // Task Model C ...