A
A
artuh_a2020-05-19 12:52:03
JavaScript
artuh_a, 2020-05-19 12:52:03

How to solve CORS error: "Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request."?

I fasten authorization through a Google account.

Nodejs server on Koa http://localhost:3000, front - react http://localhost:8000.

I create a request on the client:

login: () => {
    const request = new Request('http://localhost:3000/auth/google', {
      credentials: 'include',
      headers: new Headers({
        'Access-Control-Allow-Headers': 'Content-Type',
        'Access-Control-Allow-Credentials': true,
        'Content-Type': 'application/json',
      }),
    });
    return fetch(request)
      .then((response) => {
        if (response.status < 200 || response.status >= 300) {
          throw new Error(response.statusText);
        }
        return response.json();
      })
      .then(({ token }) => {
        localStorage.setItem('token', token);
      });
  }


On the server I process it:
authModule.initPassportStrategies(passport);

apiAuthRouter
  .get(
    '/auth/google',
    passport.authenticate('google', {
      scope: ['profile', 'email'],
    }),
  )
  .get('/auth/google/callback', (ctx) => {
    return passport.authenticate('google', (err, user) => {
      if (user) {
        ctx.login(user);
      }

      ctx.redirect('http://localhost:8000');
    })(ctx);
  });


For authorization with google I use the module passport-google-oauth:
function initPassportStrategies() {
  passport.serializeUser((user, done) => {
    done(null, user);
  });
  passport.deserializeUser((user, done) => {
    done(null, user);
  });

  passport.use(
    new GoogleStrategy(
      {
        clientID,
        clientSecret,
        callbackURL: 'http://localhost:4000',
      },
      (token, refreshToken, profile, done) => {
        return done(null, { profile, token });
      },
    ),
  );
}


Immediately after the request, an error is thrown:
Access to fetch at 'https://accounts.google.com/o/oauth2/v2/auth?...' (redirected from 'http://localhost:4000/auth/google') from origin 'http://localhost:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.


Here are the queries themselves:
Request URL: http://localhost:4000/auth/google
Request Method: GET
Status Code: 302 Found
Remote Address: [::1]:4000
Referrer Policy: no-referrer-when-downgrade
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:8000
Connection: keep-alive
Content-Length: 5
Content-Type: text/plain; charset=utf-8
Date: Tue, 19 May 2020 09:22:29 GMT
Location: https://accounts.google.com/o/oauth2/v2/auth?...
Vary: Origin
accept: application/json
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8,ru;q=0.7
access-control-allow-credentials: true
access-control-allow-headers: Content-Type
access-control-allow-methods: GET
access-control-allow-origin: http://localhost:8000
Cache-Control: no-cache
Connection: keep-alive
content-type: application/x-www-form-urlencoded
Host: localhost:4000
Origin: http://localhost:8000
Pragma: no-cache
Referer: http://localhost:8000/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: ...


Request URL: https://accounts.google.com/o/oauth2/v2/auth?...
Provisional headers are shown
Referer: http://localhost:8000/
User-Agent: ...
response_type: code
redirect_uri: http://localhost:4000/auth/google/callback
scope: profile email
client_id: ...


If you directly follow the link localhost:3000/auth/google from the client, the screen with Google authorization opens.

From the article I tried to specify headers in the request:
Access-Control-Allow-Origin: http://localhost:8000
Access-Control-Allow-Methods: GET
Access-Control-Allow-Headers: Content-Type

- it did not give any result.

Can someone tell me how to properly configure CORS in my case, or at least push in the right direction, what else can I try to do?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Igor, 2020-05-19
@loonny

Your localhost is only available to you. Just translate the error

CORS: "Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request."
CORS: "Response to preflight request fails access control check: Redirect not allowed for preflight request."

K
Konstantin, 2020-05-19
@jcricket

Try adding bold to your code

const request = new Request('http://localhost:3000/auth/google', {
      credentials: 'include',
     <b> mode: 'cors' </b>  <i>// no-cors, *cors, same-origin</i>
      headers: new Headers({
        ....
      }),
    });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question