Manage passportjs Google-Strategy in a Vue App

378 Views Asked by At

I would like to integrate the Google-strategy of passportjs in my Vue App (Node is running in back-end).

Vue app is running on localhost:8080 and Node is running on localhost:5000

I set up a Local-strategy (which is working) like this :

  • Axios.post from the Vue App to the authentification route
  • Check and validate the user/passport in my route and send a JWT Token to the Vue App
  • Store the token in the local storage

I would like to do the same thing for the Google-strategy but I cannot send the token because of the redirection.

Here is my code :

google-strategy-route.js

router.get(
    '/google',
    passport.authenticate('google', {
        scope: ['profile', 'email'],
    })
);

router.get(
    '/google/callback',
    passport.authenticate('google', {
        failureRedirect: '/',
        session: false,
    }),
    (req, res) => {
        const payload = {
            user: {
                id: req.user._id,
            },
        };
        jwt.sign(payload, process.env.jwtSecret, (err, token) => {
            if (err) throw err;
            res.json({ token });
        });
    }
);

google-strategy-auth.js

passport.use(
        new GoogleStrategy(
            {
                clientID: process.env.GOOGLE_CLIENT_ID,
                clientSecret: process.env.GOOGLE_CLIENT_SECRET,
                callbackURL: 'http://localhost:5000/api/auth/google/callback',
                passReqToCallback: true,
                proxy: true,
            },
            async function (request, accessToken, refreshToken, profile, done) {
                try {
                    const existingUser = await User.findOne({ email: profile.email });
                    if (existingUser) {
                        return done(null, existingUser);
                    }
                } catch (err) {
                    console.log(err);
                }
                try {
                    done(null, newUser);
                } catch (err) {
                    console.log(err);
                }
            }
        )
    );

In the Vue app, I have a href to /api/auth/google

<a href="/api/auth/google">Connexion Google</a>

Does anyone have an idea ?

Thanks !

1

There are 1 best solutions below

0
On

Finally, I have decided not to use passportjs. As it is a Node middleware, it was quite complicated to redirect with a token. I used the Javascript SDK to integrate the connection pop-up and when the user is logged, I check in the back the value of the token sent by the front and get the user infos. The check in the back is managed by the Auth Library of Google : https://github.com/googleapis/google-auth-library-nodejs

Hope this answer will help someone !