Hi there.
I have NextJS frontend using the Pages Router and Express API. Some API actions require the user to be authenticated. The API request is returning an “InvalidTokenError: Invalid URL”. Curiously, the access token I get back has an array for the audience in the payload - one value is the API identifier (which I would expect) (http://localhost:5500/api/v1/example) and the other is the application domain with the path “userinfo” (https://example.ca.auth0.com/userinfo).
The general setup is as follows:
// pages/api/auth/[...auth0].ts
import { handleAuth, handleLogin } from "@auth0/nextjs-auth0";
export default handleAuth({
login: handleLogin({
authorizationParams: {
audience: "http://localhost:5500/api/v1/example", // taken from API identifier in Auth0 dashboard
scope: "openid profile email read:example",
},
}),
});
// pages/index.tsx
import { Button } from "@/components/ui/button";
import { getAccessToken } from "@auth0/nextjs-auth0";
export default function Home({ accessToken }) {
return (
<>
<Button
onClick={async () => {
await fetch("http://localhost:5500/api/v1/example", {
headers: {
Authorization: `Bearer ${accessToken}}`,
},
});
}}
>
Test Button
</Button>
</>
);
}
export async function getServerSideProps(ctx) {
try {
const { accessToken } = await getAccessToken(ctx.req, ctx.res);
return { props: { accessToken } };
} catch (error) {
console.log(error);
return { props: { stories: [], accessToken: "" } };
}
}
// middleware/auth0.middleware.ts (express middleware)
import { auth } from "express-oauth2-jwt-bearer";
import dotenv from "dotenv";
dotenv.config();
export const validateAccessToken = auth({
issuerBaseURL: process.env.AUTH0_DOMAIN, // http://localhost:5500/api/v1/example
audience: process.env.AUTH0_AUDIENCE, // example.ca.auth0.com/userinfo
});
Any thoughts what might be causing the error? Much thanks for your help!