Cross-Origin Request Blocked with google oauth in react and deno

Viewed 187

I have a deno server using oak:

import { CORS } from "https://deno.land/x/oak_cors@v0.1.1/mod.ts";
export { Application } from "https://deno.land/x/oak@v10.5.1/mod.ts";


const app = new Application();

app.use(CORS({
    origin: '*', credentials: true
}))

app.use('/auth/google/url', (ctx) => {
 const oauth2Client = new OAuth2Client({
      clientId: env.get("CLIENTID") as string,
      clientSecret: env.get("CLIENTSECRET") as string,
      redirectUri: env.get("REDIRECTURI") as string,
      authorizationEndpointUri: env.get("AUTHORIZATIONENDPOINTURI") as string,
      tokenUri: env.get("TOKENURI") as string,
      defaults: {
        scope: "profile email openid",
      },
    });
  ctx.response.redirect(
      return oauth2Client.code.getAuthorizationUri();
    );
});

I call the api from the react app:

import React from 'react'

export default function App(){
  const handleClick = () => {
     fetch('/auth/google/url', {method: 'get', redirect: 'follow'})
    .then((response) => {
      if (response.status === 302) {
        window.location.href = response.url
      }
    })

  }

  return(
    <Button onClick={handleClick}>SignIn with Google</Button>
  )

}

I set the proxy in the package.json:

"proxy": "http://127.0.0.1:5000"

I got this error in the browser console:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=XXXXXXXXXXX&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2Fauth%2Fgoogle%2Fcallback&scope=profile+email+openid. (Reason: CORS request did not succeed). Status code: (null).
1 Answers

I fixed the issue by updating the api, so instead of redirecting the user to the callback page I return the url and the status code:

app.use('/auth/google/url', (ctx) => {
 const oauth2Client = new OAuth2Client({
      clientId: env.get("CLIENTID") as string,
      clientSecret: env.get("CLIENTSECRET") as string,
      redirectUri: env.get("REDIRECTURI") as string,
      authorizationEndpointUri: env.get("AUTHORIZATIONENDPOINTURI") as string,
      tokenUri: env.get("TOKENURI") as string,
      defaults: {
        scope: "profile email openid",
      },
    });

      ctx.response.body = oauth2Client.code.getAuthorizationUri();
      ctx.response.status = 302
});

So the button handler is updated like this:

const handleClick = async () => {
   const response =  await fetch('http://localhost:3000/auth/google/url')
   const data = await response.json()
   if (data) {
     window.location.href = data
   }
  }
Related