pilcrowOnPaper / arctic

OAuth 2.0 clients for popular providers
MIT License
886 stars 58 forks source link

google.validateAuthorizationCode() get 'Fail Fetch ' error #164

Closed heavenmei closed 1 month ago

heavenmei commented 1 month ago

When I use google.validateAuthorizationCode() get error. Here is my code

export async function google(c: Context<{ Variables: ContextVariables }>) {
  const state = generateState();
  const codeVerifier = generateCodeVerifier();

  const url = await googleAuth.createAuthorizationURL(state, codeVerifier, {
    scopes: ['profile', 'email'],
  });

  const opt = {
    secure: serverEnvs.NODE_ENV === 'production', // set to false in localhost
    path: '/',
    httpOnly: true,
    maxAge: 60 * 10, // 10 min
  };

  setCookie(c, 'state', state, opt);

  // store code verifier as cookie
  setCookie(c, 'code_verifier', codeVerifier, opt);

  return c.redirect(url.toString());
}
export async function googleCallback(c: Context<{ Variables: ContextVariables }>) {
  const code = c.req.query('code')?.toString() ?? null;
  const state = c.req.query('state')?.toString() ?? null;

  const storedState = getCookie(c, 'state') ?? null;
  const storedCodeVerifier = getCookie(c, 'code_verifier') ?? null;

  if (!code || !storedState || !storedCodeVerifier || state !== storedState) {
    return c.body('Invalid request', 400);
  }

  try {
    const tokens = await googleAuth.validateAuthorizationCode(code, storedCodeVerifier);

    return c.json(successRes({}));
  } catch (e) {
    console.log(e);
    if (e instanceof OAuth2RequestError) {
      // Invalid authorization code, credentials, or redirect URI
      return c.json(failRes({ message: e.code }));
    }
    if (e instanceof ArcticFetchError) {
      // Failed to call `fetch()`
      return c.json(failRes({ message: e.cause }));
    }

    return c.json(failRes({ message: e }));
  }
}
image
pilcrowOnPaper commented 1 month ago

I really doubt this is an issue with Arctic, unless it's sending a request to an endpoint that doesn't exist. Not sure if there's anything we could do honestly