OAuth2 - Error 400 : redirect_uri_mismatch with Passport, Redirect URL is different than what was set

1.1k Views Asked by At

I tried to implement google OAuth2 to my express API with passport, but I get the error :

enter image description here

---------------------------------------------
The users.js route file:

...
const GoogleStrategy = require('passport-google-oauth20').Strategy
...

passport.use(new GoogleStrategy(
    {
        clientID: process.env.GOOGLE_CLIENT_ID,
        clientSecret: process.env.GOOGLE_CLIENT_SECRET,
        callbackURL: 'users/auth/google/callback'
    }, accessToken => {
        console.log(accessToken);
    }
    )
)
...
router.get('/auth/google', passport.authenticate('google', {scope: ['profile', 'email']}))
...

In the Google developers console I set the Authorized redirect URIs to :

http://localhost:3000/users/auth/google/callback My client ID and secret are correct.

In the errror message, I can see the redirect URI is : http://localhost:3000/auth/users/auth/google/callback

There is an additional auth in the beginning of the Url path, which is strange because I haven't set it. How can I remove it? Can I even remove it?

2

There are 2 best solutions below

0
On

To start with, you made a callback url to 'users/auth/google/callback', so you have to create it:

router.get('users/auth/google/callback', 
  passport.authenticate('google', { failureRedirect: '/login' }),
  function(req, res) {
    // Successful authentication, redirect home.
    res.redirect('/');
  });
0
On

Had the same issue. Solved it with replacing the url"/users/auth/google/callback" in the new GoogleStrategy with the full url: https://{my-domain}/users/auth/google/callback. for some reason google were looking for an http url and adding the full one with 'https' solved it.

passport.use(new GoogleStrategy({
    clientID: process.env.OAUTH2_ID,
    clientSecret: process.env.OAUTH2_SECRET,
    callbackURL: "https://{your-domain}/users/auth/google/callback"
  },
  async (accessToken, refreshToken, profile, done) => {
Your code goes here

});