Restrict login to specific domain using Node Passport with Google Auth

前端 未结 2 2188
陌清茗
陌清茗 2021-01-31 20:07

I am implementing Google Auth on an internal service at work. It is a JS client heavy application with a Node backend. I am choosing to use the Node module Passport.js with the

2条回答
  •  忘掉有多难
    2021-01-31 20:48

    I recommend a 2 step approach to this. Would love to hear feedback if this is overcomplicating it.

    1) Help your users pick the right account

    passport.authenticate('google', {
        // Only show accounts that match the hosted domain.
        hd: 'example.com',
        // Ensure the user can always select an account when sent to Google.
        prompt: 'select_account',
        scope: [
            'https://www.googleapis.com/auth/plus.login',
            'https://www.googleapis.com/auth/plus.profile.emails.read'
        ]
    })(req, res, next);
    

    2) Validate their profile

    When a user is sent to accounts.google.com to authenticate, there is a simple hd=example.com query parameter in the URL. You can remove this and authenticate with any account (Passport will successfully verify the Oauth code regardless of the domain of the chosen account), so it should only be considered sugar for the end user and not security for the server.

    When Passport does resolve the authentication, just check the hosted domain as in aembke's answer:

    passport.use(new google_strategy({
        clientID: ...
        clientSecret: ...
        callbackURL: ...
    }, function(token, tokenSecret, profile, done) {
    
        if (profile._json.domain !== 'example.com') {
            done(new Error("Wrong domain!"));
        } else {
            done(null, profile);
        }
    
    }));
    

提交回复
热议问题