Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Token refresh in middleware causing issues #1184

Open
kevinmitch14 opened this issue Dec 9, 2024 · 8 comments
Open

Token refresh in middleware causing issues #1184

kevinmitch14 opened this issue Dec 9, 2024 · 8 comments

Comments

@kevinmitch14
Copy link

kevinmitch14 commented Dec 9, 2024

Hi,

We are using the Node SDK in our nextjs application. We are running into issues in relation to refreshing the tokens in middleware.

Basically, when using something like tanstack query, and refocusing on the window, it will refetch the queries. We have some queries pointing to our API route handlers. This works okay, until the token needs to be refreshed, it then seems that my custom assert session helper doesn't pick up the session. Any ideas as to why?

This is working perfectly, until the refetch on window focus occurs and refresh token needs to be refreshed

export const assertSession = async () => {
  if (typeof window !== "undefined") {
    throw new Error("getSession can not be used on the client");
  }

  const cookieStore = await cookies();
  const workosCookie = cookieStore.get(WORK_OS_COOKIE_NAME)?.value;

  if (!workosCookie) {
    redirect("/sign-in");
  }

  const session = loadSealedSession(workosCookie);

  const authSession = await session.authenticate();

  if (!authSession.authenticated) {
    redirect("/sign-in");
  }

  return authSession;
};

This is what I'm observing in the logs

Screenshot 2024-12-09 at 12 51 34
@kevinmitch14
Copy link
Author

And in the case of using the nextjs library version, with a custom UI, is it possible to use to use authMiddleware? Because we do not want to use hosted authkit, we want a simple magic auth sign in at the /sign-in route. But it seems the middleware wants redirect to a callback URL?

@PaulAsjes
Copy link
Contributor

For your first question, there's not a lot to go on with what you've provided. I suggest adding more logging to see what the problem might be. authSession in your code will have a reason parameter if authenticated === false. I suggest starting there.

As for the Next.js library, it will currently only work if you use AuthKit rather than your own UI. When using your own UI we recommend using the Node SDK instead.

@kevinmitch14
Copy link
Author

Hey Paul, the reason is invalid_jwt. I think it is because, the updated cookie in middleware is not directly available in the route handler. I believe this is why there is getSession() (which only works in nextjs middleware) and withAuth() which works outside of nextjs middleware, in the nextjs library.

withAuth() reads the session from the headers it seems, while the getSession() reads from cookies. And the Authkit middleware, does some header manipulation to help make all this work. Because setting a cookie and directly hitting an API route handler would not work.

To achieve a custom UI + nextjs middleware, with the node sdk, I would need to do all this header manipulation too right?

Would an option be to use the authkit middleware without middlewareAuth enabled, and manage this myself. Maybe a best of both worlds? Something like this - https://github.com/workos/authkit-nextjs?tab=readme-ov-file#retrieve-session-in-middleware. Because with middlewareAuth enabled, middleware just wants to redirect to the hosted authkit domain.

Using the authkit middleware eliminates issues with manual refreshing/header manipulation etc. (Session is available in route handlers etc)

@kevinmitch14
Copy link
Author

kevinmitch14 commented Dec 10, 2024

Could you confirm if this example actually works? I am getting really strange results here. Debug logs say session is valid, but when I check getSession() like in the docs, there is no session. I am using the exact same code as shown in the readme.

The debug logs from the middleware say there is a session.
But logging the session like in the example, states otherwise.

https://github.com/workos/authkit-nextjs?tab=readme-ov-file#retrieve-session-in-middleware

@DarrylBrooks97
Copy link

DarrylBrooks97 commented Dec 12, 2024

I'm running into a similar issue with an invalid_grant when refreshing a session token within middleware 🤔

@PaulAsjes
Copy link
Contributor

@kevinmitch14 Are you using the provided middleware or are you using your own custom middleware with custom UI? invalid_jwt indicates that the access token is invalid, likely due to it being expired.

@DarrylBrooks97 You should receive a description alongside that error that will give more clues as to what's going on. i.e. "Refresh token already used". Can you share the description?

@DarrylBrooks97
Copy link

My issue turned out to be that setting a cookie using the cookies() function within middleware did not propagate to my server components. Therefore when trying to authenticate the session within the component it used an expired accessToken. My solution was to just set the cookie on the returned middleware response

@monolithed
Copy link

monolithed commented Jan 11, 2025

@PaulAsjes,
I also occasionally encounter the following error when updating the token:

Screenshot 2025-01-11 at 17 37 44

I found the only mention of the invalid_grant error in this PR: #1078. Why is it being returned and how should it be handled?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

4 participants