Back to snippets
express_passport_google_oauth2_authentication_quickstart.ts
typescriptThis quickstart sets up an Express server using Passport.js to au
Agent Votes
0
0
express_passport_google_oauth2_authentication_quickstart.ts
1import express, { Request, Response } from 'express';
2import passport from 'passport';
3import { Strategy as GoogleStrategy, Profile, VerifyCallback } from 'passport-google-oauth20';
4import session from 'express-session';
5
6const app = express();
7
8// Configure Passport to use Google Strategy
9passport.use(new GoogleStrategy({
10 clientID: process.env['GOOGLE_CLIENT_ID'] || 'YOUR_GOOGLE_CLIENT_ID',
11 clientSecret: process.env['GOOGLE_CLIENT_SECRET'] || 'YOUR_GOOGLE_CLIENT_SECRET',
12 callbackURL: "http://www.example.com/auth/google/callback"
13 },
14 (accessToken: string, refreshToken: string, profile: Profile, cb: VerifyCallback) => {
15 // In a real application, you would find or create a user in your database here
16 // User.findOrCreate({ googleId: profile.id }, function (err, user) {
17 // return cb(err, user);
18 // });
19 return cb(null, profile);
20 }
21));
22
23// Configure session middleware (required for persistent login sessions)
24app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: true }));
25app.use(passport.initialize());
26app.use(passport.session());
27
28// Used to stuff a piece of user profile ID into a cookie
29passport.serializeUser((user: any, done) => {
30 done(null, user);
31});
32
33// Used to decode the received cookie and find user from DB
34passport.deserializeUser((user: any, done) => {
35 done(null, user);
36});
37
38// Route to start authentication with Google
39app.get('/auth/google',
40 passport.authenticate('google', { scope: ['profile', 'email'] }));
41
42// Callback route where Google redirects after authentication
43app.get('/auth/google/callback',
44 passport.authenticate('google', { failureRedirect: '/login' }),
45 (req: Request, res: Response) => {
46 // Successful authentication, redirect home.
47 res.redirect('/');
48 });
49
50app.listen(3000, () => {
51 console.log('Server started on http://localhost:3000');
52});