2
votes

I am creating a backend which relies in Express and GraphQL which will serve clients apps (android and react).

I have been following this article on how to nail social authentication in GraphQL using passport.js.

The article uses passport-google-token strategy and is based on Apollo-server but personally I prefer to use express-graphql.

After setting my android app to use google auth and try to send mutation to server I get this error

Google info:  { InternalOAuthError: failed to fetch user profile
    at E:\_Projects\myProject\myProject-backend\node_modules\passport-google-token\lib\passport-google-token\strategy.js:114:28
    at passBackControl (E:\_Projects\myProject\myProject-backend\node_modules\oauth\lib\oauth2.js:132:9)
    at IncomingMessage.<anonymous> (E:\_Projects\myProject\myProject-backend\node_modules\oauth\lib\oauth2.js:157:7)
    at IncomingMessage.emit (events.js:194:15)
    at endReadableNT (_stream_readable.js:1125:12)
    at process._tickCallback (internal/process/next_tick.js:63:19)
    name: 'InternalOAuthError',
        message: 'failed to fetch user profile',
        oauthError:
    { statusCode: 401,
        data:
        '{\n  "error": {\n    "code": 401,\n    "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",\n    "status": "UNAUTHENTICATED"\n  }\n}\n' } }

I believe token I pass maybe does not reach where it supposed but I cant figure out how to solve.

I have tested my token here https://oauth2.googleapis.com/tokeninfo?id_token=MyToken and they are working correctly.

Here is graphQL config in app.js

app.use('/graphql', graphqlHTTP((req, res) => ({
    schema,
    graphiql: true,
    context: {req, res}
})));

Here is google auth mutation

        googleAuth: {
            type: authPayLoad,
            args: {token: {type: new GraphQLNonNull(GraphQLString)}},
            async resolve(_, {token}, {req, res}) {
                req.body = {
                    ...req.body,
                    access_token: token,
                };

                try {
                    const {data, info} = await authenticateGoogle(req, res);
                    console.log("Google data: ", data);

                    if (data) {
                        const user = await User.upsertGoogleUser(data);

                        if (user) {
                            return ({
                                name: user.name,
                                username: user.username,
                                token: user.generateJWT(),
                            });
                        }
                    }

                    if (info) {
                        console.log("Google info: ", info);

                        switch (info.code) {
                            case 'ETIMEDOUT':
                                return (new Error('Failed to reach Google: Try Again'));
                            default:
                                return (new Error('something went wrong'));
                        }
                    }
                    return (Error('server error'));

                } catch (e) {
                    console.log("Error: ", e);
                    return e
                }
            },
        },

And here is my auth controller

const passport = require('passport');
const {Strategy: GoogleTokenStrategy} = require('passport-google-token');

// GOOGLE STRATEGY
const GoogleTokenStrategyCallback = (accessToken, refreshToken, profile, done) => done(null, {
    accessToken,
    refreshToken,
    profile,
});

passport.use(new GoogleTokenStrategy({
    clientID: 'MY_CLIET_ID',
    clientSecret: 'SERVER-SECRET'
}, GoogleTokenStrategyCallback));

module.exports.authenticateGoogle = (req, res) => new Promise((resolve, reject) => {
    passport.authenticate('google-token', {session: false}, (err, data, info) => {
        if (err) reject(err);
        resolve({data, info});
    })(req, res);
});

I expected when client app submit mutation with token as arg the request will be sent to google and returns user data. How do I solve this.

1

1 Answers

2
votes

passport-google-token is archived and seems deprecated to me. Why don't you try passport-token-google. It can be used in similar way.

passport.use(new GoogleStrategy({
        clientID: keys.google.oauthClientID,
        clientSecret: keys.google.oauthClientSecret
    },
    function (accessToken, refreshToken, profile, done) {
        return done(null, {
            accessToken,
            refreshToken,
            profile,
        });
    }
));

module.exports.authenticate = (req, res) => new Promise((resolve, reject) => {
    passport.authenticate('google-token', {session: false}, (err, data, info) => {
        if (err) reject(err);
        resolve({data, info});
    })(req, res);
});

Hope this helps.