Giter VIP home page Giter VIP logo

Comments (9)

tak0m0 avatar tak0m0 commented on August 24, 2024 5

I having the same problem. I think that problem is very serious, is there any progress??😢

from kinde-auth-nextjs.

Thinkscape avatar Thinkscape commented on August 24, 2024

Here's a snippet from my custom TS implementation of the AuthProvider that supports token refresh:

// Auto-refresh token before it expires
  useEffect(() => {
    let timeoutId: Timer;

    const scheduleTokenRefresh = () => {
      if (state.accessToken) {
        try {
          const expClaim = state.getClaim("exp", "access_token");
          if (expClaim && typeof expClaim.value === "number") {
            const currentTime = Math.floor(Date.now() / 1000);
            const timeToExpiry = expClaim.value - currentTime;

            // Refresh the token 60 seconds before it actually expires
            if (timeToExpiry > 60) {
              timeoutId = setTimeout(
                // eslint-disable-next-line @typescript-eslint/no-misused-promises
                async () => {
                  await checkSession();
                },
                (timeToExpiry - 60) * 1000,
              );
            }
          }
        } catch (error) {
          console.error("Error fetching exp claim:", error);
        }
      }
    };

    void scheduleTokenRefresh();

    return () => {
      timeoutId && clearTimeout(timeoutId);
    };
  }, [state.accessToken, state.getClaim, checkSession, state]);

Note: checkSession() is a fixed and cleaned up TS version of https://github.com/kinde-oss/kinde-auth-nextjs/blob/main/src/frontend/AuthProvider.jsx#L61

from kinde-auth-nextjs.

Thinkscape avatar Thinkscape commented on August 24, 2024

Here's a TS implementation of tokenFetcher() with support for redirecting the browser session to login page in case auth has expired while the page is still open:

const tokenFetcher = async (
  url: string,
  router: ReturnType<typeof useRouter>,
): Promise<KindeSetupResponse | undefined> => {
  let response;
  try {
    response = await fetch(url);
  } catch (e) {
    throw new Error("AuthProvider: Failed to fetch auth data", {
      cause: e as Error,
    });
  }

  if (response.ok) {
    return await response.json();
  } else {
    if (response.status === 401) {
      const loginUrl = response.headers.get("location") || LOGIN_PAGE;
      logger.debug(
        "AuthProvider: Auth token expired, redirecting to login page",
        { location: loginUrl },
      );
      router.push(loginUrl);
    } else {
      logger.error(
        "AuthProvider: Unknown error while trying to obtain auth data",
        {
          response: {
            status: response.status,
            statusText: response.statusText,
          },
        },
      );
    }
  }
};

from kinde-auth-nextjs.

peterphanouvong avatar peterphanouvong commented on August 24, 2024

Extremely sorry for letting this one slip through - I'll be better at addressing these issues.
I'm assuming this is for Pages router?

I'll prioritise this!

from kinde-auth-nextjs.

tak0m0 avatar tak0m0 commented on August 24, 2024

Thank you! I think this problem is also happen in app router.

from kinde-auth-nextjs.

peterphanouvong avatar peterphanouvong commented on August 24, 2024

Hey @tak0m0 would you be able to share any extra details or code snippets to help me reproduce this error in the App Router w/ useKindeBrowserClient

from kinde-auth-nextjs.

tak0m0 avatar tak0m0 commented on August 24, 2024

I’m using “useKindeBrowserClient” in the header and user menu, but it doesn’t handle expired sessions and re-authentication. It often returns a 401 error. Many authentication libraries try to authenticate again with a refresh token even if the main token has expired, but this does not appear to be possible with this library.
I set a 1,296,000 seconds refresh token expiry but realized that it expires earlier than that time.
image

from kinde-auth-nextjs.

peterphanouvong avatar peterphanouvong commented on August 24, 2024

Hey guys, I made a release 2.3.7-beta.20 which should fix the problems. It's still in beta because it needs some testing.

from kinde-auth-nextjs.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.