Home  >  Q&A  >  body text

fetch access to https://accounts.google .com/o/oauth2/v2/auth blocked by CORS

I'm sending a fetch from React to Express to authenticate with Google, but my access is blocked by a CORS error. I'm redirecting POST requests from React to a Google URL for authentication. I tried using cors in an Express application but still got the same error. Used to get

const handleClick = (e) => {
    fetch('http://localhost:8000/api/mail/login', {
        method: 'POST'
    })
    .then(res => res.text())
}

Using cors in Express app.js

app.use(cors())

Attempt to redirect to Google Authentication

const oauth2Client = new google.auth.OAuth2(
    process.env.CLIENT_ID,
    process.env.CLIENT_SECRET,
    process.env.REDIRECT_URI
)

const url = oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: process.env.SCOPE
})

const gmail = google.gmail({
    version: 'v1',
    auth: oauth2Client
})

router.post('/login', (req, res, next) => {
    res.redirect(url)
})

Error: Accessing "https://accounts.google .com/o/oauth2/v2/auth?access_type=offline&scope=https://mail.google.com/&response_type=code&client_id=727520060136" for extraction - ngpfd4ll798v42gfclh7cms9ndqstt32. apps.googleusercontent.com&redirect_uri=http://localhost:8000' (redirected from 'http://localhost:8000/api/mail/login') from origin 'http://localhost:3000' has been blocked by CORS policy : The 'Access-Control-Allow-Origin' header does not exist on the requested resource. If an opaque response meets your needs, set the request mode to "no-cors" to get the resource with CORS disabled.

P粉398117857P粉398117857321 days ago720

reply all(1)I'll reply

  • P粉201448898

    P粉2014488982023-11-04 09:56:59

    The authentication flow must occur within a visible browsing context , without using a fetch request. In other words: you must navigate the current tab to (or open a new tab) http://localhost:8000/api/mail/login, which will be Redirect to https://accounts.google.com/o/oauth2/v2/auth?... and the page becomes visible. The user must now interact with the page to select/confirm their Google account, after which they will be redirected to a page on your server with the authorization code in the URL (for example, http://localhost:8000/callback? code =...) and your server must exchange the authorization code for the access token via a server-to-server call.

    The requests issued in this way are not cross-origin, so CORS will not be involved at all.

    You need a similar login form instead of the handleClick function

    <form action="http://localhost:8000/api/mail/login" method="post">
      <input type="submit" value="Press to log in"/>
    </form>
    

    reply
    0
  • Cancelreply