Call NextJS Auth0 protected API from React Native app

I have a NextJS app that’s protected by the withMiddlewareAuthRequired function from the @auth0/nextjs-auth0/edge package. The middleware.js file looks like this.

import { withMiddlewareAuthRequired } from '@auth0/nextjs-auth0/edge'

export default withMiddlewareAuthRequired()

I want to make calls to the server actions of this app from a React Native app that uses the react-native-auth0 package.

I’ve tried making the call by adding the idToken to the Authorization header.

And I’ve tried manually constructing the cookie based on what I see when I inspect the API calls to the server actions in the browser network tab.

const credentials = await auth0.credentialsManager.getCredentials()
const cookie = `appSession=${credentials.idToken}`

const res = fetch(nextJsServerActionUri, {
  headers: {
    Cookie: cookie,
  },
})

const res = fetch(nextJsServerActionUri, {
  headers: {
    Authorization: `Bearer ${credentials.idToken}`,
    'Content-Type': 'application/json',
  },
})

Neither of these is working. I’m getting 401 unauthorized responses.

The call succeeds if I copy the cookie directly from the network tab in the browser console when making a call to the NextJS server action, and paste it into the cookie variable in the code above.

It seems the cookie I’m trying to build is missing something. There are a lot of values that I’m not sure where they’re coming from.

Am I on the right track?

Hey there @Outbound5070 welcome to the community!

I’m unfortunately not familiar with using nextjs-auth0 to protect an API in this way, but the standard approach in all our backend SDKs is to pass an access token and verify it as opposed to an ID token. Here are some quickstarts which may be helpful:

Hey @tyf thank you for getting back to me so quickly.

I’ve tried adding every value I get from auth0.credentialsManager.getCredentials() to the Authorization header and none of them work.

The NextJS endpoint is using a cookie to authenticate.

It has many values. Including:

_xsrf=
username-localhost-8888=
appSession=

Is there a way to find out how those cookie values are generated so I can create my own?

No problem, happy to help where I can!

Please see my response to your other topic:

As far as I can tell the nextjs-auth0 SDK isn’t going to play nicely with react-native-auth0 - credentialsManager deals with tokens only.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.