3 Hours

11. Social Login with Google & GitHub OAuth

Social Login

Social login allows users to authenticate using their existing Google, GitHub, or other accounts. This module covers integrating OAuth2 providers, handling callbacks, and linking social accounts.

How Social Login Works

The flow is similar to standard OAuth2, but the goal is to get user profile information for authentication.

Text
1. User clicks "Login with Google"
2. Redirect to Google's OAuth2 authorization page
3. User approves requested scopes (email, profile)
4. Google redirects back with authorization code
5. Your server exchanges code for tokens
6. Your server fetches user profile using the token
7. Your server creates/updates user in database
8. Your server issues your own JWT (or creates session)
Important: After social login, your app should issue its own authentication token (JWT or session). Never rely solely on the provider's token.

Setting Up OAuth Credentials

Before coding, register your app with the provider to get credentials.

Text
Google Cloud Console:
1. Go to console.cloud.google.com
2. Create a new project
3. Enable Google+ API
4. Create OAuth 2.0 credentials
5. Set redirect URI: http://localhost:3000/auth/google/callback

GitHub Developer Settings:
1. Go to github.com/settings/developers
2. Register new OAuth App
3. Set Homepage URL: http://localhost:3000
4. Set callback URL: http://localhost:3000/auth/github/callback

Google OAuth Integration (Node.js)

Using Passport.js for Google OAuth.

JavaScript
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;

passport.use(new GoogleStrategy({
    clientID: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    callbackURL: '/auth/google/callback',
    scope: ['profile', 'email']
}, async (accessToken, refreshToken, profile, done) => {
    // Find or create user in your database
    let user = await db.users.findOne({ email: profile.emails[0].value });

    if (!user) {
        user = await db.users.create({
            email: profile.emails[0].value,
            name: profile.displayName,
            avatar: profile.photos[0]?.value,
            authProvider: 'google',
            providerId: profile.id
        });
    }

    return done(null, user);
}));

// Routes
app.get('/auth/google', passport.authenticate('google'));

app.get('/auth/google/callback',
    passport.authenticate('google', { failureRedirect: '/login' }),
    (req, res) => {
        const token = jwt.sign({ userId: req.user.id }, SECRET_KEY);
        res.redirect(`/auth-success?token=${token}`);
    }
);

GitHub OAuth Integration (Node.js)

JavaScript
const GitHubStrategy = require('passport-github2').Strategy;

passport.use(new GitHubStrategy({
    clientID: process.env.GITHUB_CLIENT_ID,
    clientSecret: process.env.GITHUB_CLIENT_SECRET,
    callbackURL: '/auth/github/callback'
}, async (accessToken, refreshToken, profile, done) => {
    let user = await db.users.findOne({ email: profile.emails[0]?.value });

    if (!user) {
        user = await db.users.create({
            email: profile.emails[0]?.value || `${profile.username}@github.com`,
            name: profile.displayName || profile.username,
            avatar: profile.photos[0]?.value,
            authProvider: 'github',
            providerId: profile.id
        });
    }

    return done(null, user);
}));

app.get('/auth/github', passport.authenticate('github', { scope: ['user:email'] }));

app.get('/auth/github/callback',
    passport.authenticate('github', { failureRedirect: '/login' }),
    (req, res) => {
        const token = jwt.sign({ userId: req.user.id }, SECRET_KEY);
        res.redirect(`/auth-success?token=${token}`);
    }
);

Linking Multiple Social Accounts

Allow users to connect multiple social accounts to the same profile.

JavaScript
// Link additional account to existing user
app.get('/auth/google/link', requireAuth, (req, res) => {
    passport.authorize('google', {
        scope: ['profile', 'email'],
        state: req.user.id
    })(req, res);
});

app.get('/auth/google/link/callback',
    passport.authorize('google'),
    async (req, res) => {
        // Link the provider account to current user
        await db.users.updateOne(
            { _id: req.user.id },
            { $set: { 'linkedAccounts.google': {
                id: req.account.providerId,
                email: req.account.email
            }}}
        );
        res.redirect('/settings');
    }
);

// Unlink social account
app.post('/auth/unlink/:provider', requireAuth, async (req, res) => {
    await db.users.updateOne(
        { _id: req.user.id },
        { $unset: { [`linkedAccounts.${req.params.provider}`]: '' } }
    );
    res.json({ message: 'Account unlinked' });
});

Frontend Redirect Handling

JavaScript
// In your React/Vue component
function LoginButtons() {
    const handleGoogleLogin = () => {
        window.location.href = 'http://localhost:3000/auth/google';
    };

    const handleGitHubLogin = () => {
        window.location.href = 'http://localhost:3000/auth/github';
    };

    return (
        <div>
            <button onClick={handleGoogleLogin}>Login with Google</button>
            <button onClick={handleGitHubLogin}>Login with GitHub</button>
); } // Auth success page to capture token function AuthSuccess() { const params = new URLSearchParams(window.location.search); const token = params.get(token); useEffect(() => { if (token) { localStorage.setItem(accessToken, token); window.location.href = /dashboard; } }, [token]); return
Logging you in...
; }

Knowledge Check

Ready to test your understanding of 11. Social Login with Google & GitHub OAuth?

Back