Why am I getting redirect_uri_mismatch error on heroku with my OAuth2 authentication?

1.2k Views Asked by At

I am using google plus API in one of my apps. It is working perfectly fine in my local repository, but on Heroku, it throws this error: Error: redirect_uri_mismatch

The redirect URI in the request, http://discuss-my-anime.herokuapp.com/auth/google/redirect, does not match the ones authorized for the OAuth client.

My google plus API credentials are given below: Google plus API credentials

I am using the passport package for the authentication process and my passport setup code is given below:

const passport = require("passport");
const GoogleStrategy = require("passport-google-oauth20");
const keys = require("./keys");
const User = require("../models/user-model");

passport.serializeUser((user, done)=>{
 done(null, user.id);
});

passport.deserializeUser((id, done)=>{
 User.findById(id).then((user)=>{
  done(null, user);
 });
});

passport.use(
 new GoogleStrategy({
  //options for google strategy
  callbackURL: "/auth/google/redirect",
  clientID: keys.google.clientID,
    clientSecret: keys.google.clientSecret
 }, (accessToken, refreshToken, profile, done)=>{
  //check if user already exists
  User.findOne({googleId: profile.id}).then((currentUser)=>{
   if(currentUser){
    //already have a user
    console.log("user is: " + currentUser);
    done(null, currentUser);
   }
   else{
    //creating new user
    new User({
     username: profile.displayName,
     googleId: profile.id,
     thumbnail: profile._json.picture
    }).save().then((newUser)=>{
     console.log("new user created: " + newUser);
     done(null, newUser);
    });
   }
  });
 })
);

1

There are 1 best solutions below

0
Yilmaz On

the reason why you are getting this error is using relative path here:

callbackURL: "/auth/google/redirect"

Since dev and prod environment urls are different we use relative path. In the end, googleStrategy will figure out what domain to put on here. That is where we get our mismatch url. In development environment it is appending on the correct domain but in production it is doing the wrong thing.

In order to make sure that traffic from our browser is routed to the correct server Heroku uses a proxy or a load balancer. The reason why googleStrategy is calculating that domain incorrectly in production is that by default, the strategy assumes that if our request from the browser ever went through any type of proxy then the request should no longer should be https because it inherently does not want to trust requests that come through a proxy. In our case we are completely trusting the heroku proxy here like our application is being hosted on heroku.

if you put the below property inside GoogleStrategy initial config object

proxy: true 

This says to GoogleStrategy if our request runs through any proxy, you can trust it.