auth0 / nextjs-auth0

Next.js SDK for signing in with Auth0
MIT License
2.08k stars 392 forks source link

withMiddlewareAuthRequired does not consider Next.js baseUrl when redirecting #1741

Open Dalimil opened 7 months ago

Dalimil commented 7 months ago

Checklist

Description

withMiddlewareAuthRequired logic doesn't work for a custom auth0 instance with custom base URL set.

https://github.com/auth0/nextjs-auth0/blob/951a24864c61eec98702f91eb7784555d54916da/src/helpers/with-middleware-auth-required.ts#L93

It should be redirecting to /foo/api/auth/login/ instead of /api/auth/login when baseURL is set in auth0 config.

The issue comes from the fact that req.pathname that is used inside the function doesn't contain Nextjs base url prefix. In your code you are first checking that in the ignorePaths the login url doesn't match the pathname. And then you use the same login url to redirect. So your logic will break either during the ignorePath matching or later when you redirect (depending on whether in your config you have the base url part of the login url or not). This was already mentioned here: https://github.com/auth0/nextjs-auth0/issues/1118

Reproduction

  1. create an auth0 instance with initAuth0(config) where you set the baseURL to your custom url such as localhost:3000/foo
  2. use withMiddlewareAuthRequired inside your middleware.ts
  3. Access your app, you will be redirected to /api/auth/login instead of /foo/api/auth/login/

Additional context

Already discussed here: https://github.com/auth0/nextjs-auth0/issues/1118

nextjs-auth0 version

3.5.0

Next.js version

13.4.12

Node.js version

18.17.1

Cpt0Teemo commented 7 months ago

Running into the same issue