Restrict login to specific domain using Node Passport with Google Auth

前端 未结 2 2181
陌清茗
陌清茗 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 21:06

    Here's an example:

    // first make sure you have access to the proper scope on your login route
    app.get("/login", passport.authenticate("google", {
        scope: ["profile", "email"]
    }));
    
    // set up your Google OAuth strategy elsewhere...
    passport.use(new GoogleStrategy({
        clientID: "something",
        clientSecret: "something",
        callbackURL: "/something"
    }, function(token, refreshToken, profile, done){
        if(profile._json.hd === "yourdomain.com"){
            // find or create user in database, etc
            User.find({ id: profile.id }).done(done);
        }else{
            // fail        
            done(new Error("Invalid host domain"));
        }
    });
    

    And for good measure here's a full variable dump of what the "profile" variable looks like.

    { 
        provider: 'google',
        id: '12345678987654321',
        displayName: 'Don Draper',
        name: { familyName: 'Whitman', givenName: 'Richard' },
        emails: [ { value: 'don@scdp.com' } ],
        _raw: 'a bunch of stringified json',
        _json: { 
            id: '123456789',
            email: 'something@something.com',
            verified_email: true,
            name: 'Don Draper',
            given_name: 'Don',
            family_name: 'Draper',
            link: 'https://plus.google.com/123456789',
            picture: 'https://lh3.googleusercontent.com/XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/123456789/photo.jpg',
            gender: 'male',
            locale: 'en',
            hd: 'yourdomain.com' 
        } 
    }
    

    Here are some detailed tutorials that should answer your question about the theory behind all of this. You'll want some combination of the two.

    1. Local authentication and basic setup
    2. Google authentication

提交回复
热议问题