Shopify / koa-shopify-auth

DEPRECATED Middleware to authenticate a Koa application with Shopify
MIT License
80 stars 63 forks source link

Verify request issue , Network error: Unexpected token U in JSON at position 0 #77

Closed psppro26 closed 1 year ago

psppro26 commented 3 years ago

I tried to simply upgrade this https://github.com/Shopify/shopify-demo-app-node-react to use session token instead of cookies on Shopify. So i followed this guide https://github.com/Shopify/koa-shopify-auth Migrating from cookie-based authentication to session tokens

Now my app look like :

server.js router.get("(.*)", verifyRequest({ accessMode: "offline" }), handleRequest); // Everything else must have sessions _app.js

function MyProvider(props) {
  const app = useAppBridge();

  const client = new ApolloClient({
    fetch: authenticatedFetch(app),
    fetchOptions: {
      credentials: "include"
    }
  });

  const Component = props.Component;

  return (
    <ApolloProvider client={client}>
      <Component {...props} />
    </ApolloProvider>
  );
}

class MyApp extends App {

  render() {
    const { Component, pageProps, shopOrigin } = this.props;

    const config = {
      apiKey: API_KEY,
      shopOrigin: shopOrigin,
      forceRedirect: true
    };

    return (
      <React.Fragment>
        <Head>
          <title>Shopy</title>
          <meta charSet="utf-8" />
        </Head>
        <Provider config={config}>
          <ClientRouter />
          <AppProvider i18n={translations}>
            <MyProvider Component={Component}>
            </MyProvider>
          </AppProvider>
        </Provider>
      </React.Fragment>
    );
  }
}

MyApp.getInitialProps = async ({ ctx }) => {
  return {
    shopOrigin: ctx.query.shop
  };
};

So the problem is with apollo , i got an error

Error: Network error: Unexpected token U in JSON at position 0 and in my ngrok i got GET /auth 400 Bad Request

Normally authenticatedFetch(app) should authenticate my graphql request , but its always hitting the /auth The bearer token is here on graphql request , but i got an UNAUTHORIZED If someone can help , it's drive me crazy

avocadoslab commented 3 years ago

I had similar auth loop but then whitelisting NextJS static content resolved it. Once you monitor network tab, you would understand who is initiator of those /auth routes.

router.get("(/_next/static/.*)", handleRequest); // Static content is clear
router.get("/_next/webpack-hmr", handleRequest); // Webpack content is clear
router.get("(.*)", verifyRequest({ accessMode: "offline" }), handleRequest);
psppro26 commented 3 years ago

Already here and issue still occurs :/ :


  const handleRequest = async (ctx) => {
    await handle(ctx.req, ctx.res);
    ctx.respond = false;
    ctx.res.statusCode = 200;
  };

  router.get("/", async (ctx) => {
    const shop = ctx.query.shop;

    // This shop hasn't been seen yet, go through OAuth to create a session
    if (ACTIVE_SHOPIFY_SHOPS[shop] === undefined) {
      ctx.redirect(`/auth?shop=${shop}`);
    } else {
      await handleRequest(ctx);
    }
  });

  router.post("/webhooks", async (ctx) => {
    try {
      await Shopify.Webhooks.Registry.process(ctx.req, ctx.res);
      console.log(`Webhook processed, returned status code 200`);
    } catch (error) {
      console.log(`Failed to process webhook: ${error}`);
    }
  });
  router.post(
    "/graphql",
    verifyRequest({ accessMode: "offline" }),
    async (ctx, next) => {
      console.log(ctx);
      await Shopify.Utils.graphqlProxy(ctx.req, ctx.res);
    }
  );
  router.get("(/_next/static/.*)", handleRequest); // Static content is clear
  router.get("/_next/webpack-hmr", handleRequest); // Webpack content is clear
  router.get("(.*)", verifyRequest({ accessMode: "offline" }), handleRequest); // Everything else must have sessions
psppro26 commented 3 years ago

I got some news , issue is same https://community.shopify.com/c/Shopify-APIs-SDKs/Offline-Access-Token-will-cause-session-not-found/m-p/1101413/thread-id/64105

work perfectly on online mode but error Error: Cannot proxy query. No session found. on offline mode

kato-takaomi-ams commented 3 years ago

@psppro26 await Shopify.Utils.graphqlProxy(ctx.req, ctx.res); works in only accessMode: "online". You can not switch it to accessMode: "offline".

cf. https://github.com/Shopify/shopify-node-api/issues/140

this is actually done by design

nitesh7039 commented 2 years ago

I tried to simply upgrade this https://github.com/Shopify/shopify-demo-app-node-react to use session token instead of cookies on Shopify. So i followed this guide https://github.com/Shopify/koa-shopify-auth Migrating from cookie-based authentication to session tokens

Now my app look like :

server.js router.get("(.*)", verifyRequest({ accessMode: "offline" }), handleRequest); // Everything else must have sessions _app.js

function MyProvider(props) {
  const app = useAppBridge();

  const client = new ApolloClient({
    fetch: authenticatedFetch(app),
    fetchOptions: {
      credentials: "include"
    }
  });

  const Component = props.Component;

  return (
    <ApolloProvider client={client}>
      <Component {...props} />
    </ApolloProvider>
  );
}

class MyApp extends App {

  render() {
    const { Component, pageProps, shopOrigin } = this.props;

    const config = {
      apiKey: API_KEY,
      shopOrigin: shopOrigin,
      forceRedirect: true
    };

    return (
      <React.Fragment>
        <Head>
          <title>Shopy</title>
          <meta charSet="utf-8" />
        </Head>
        <Provider config={config}>
          <ClientRouter />
          <AppProvider i18n={translations}>
            <MyProvider Component={Component}>
            </MyProvider>
          </AppProvider>
        </Provider>
      </React.Fragment>
    );
  }
}

MyApp.getInitialProps = async ({ ctx }) => {
  return {
    shopOrigin: ctx.query.shop
  };
};

So the problem is with apollo , i got an error

Error: Network error: Unexpected token U in JSON at position 0 and in my ngrok i got GET /auth 400 Bad Request

Normally authenticatedFetch(app) should authenticate my graphql request , but its always hitting the /auth The bearer token is here on graphql request , but i got an UNAUTHORIZED If someone can help , it's drive me crazy

suarez9093 commented 2 years ago

Was this ever resolved? Getting the same error

ViktorasssIT commented 2 years ago

Was this ever resolved? Getting the same error

Me as well getting the same error. SyntaxError: Unexpected token u in JSON at position 0

Did you find a fix?

github-actions[bot] commented 1 year ago

Note that this repo is no longer maintained and this issue will not be reviewed. Prefer the official JavaScript API library. If you still want to use Koa, see simple-koa-shopify-auth for a potential community solution.