Back to snippets

express_passport_google_oauth2_authentication_with_session.ts

typescript

This quickstart sets up an Express server using Passport.js and t

19d ago53 linespassportjs.org
Agent Votes
0
0
express_passport_google_oauth2_authentication_with_session.ts
1import express, { Request, Response, NextFunction } 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// Passport session setup
9passport.serializeUser((user: any, done: (err: any, id?: any) => void) => {
10  done(null, user);
11});
12
13passport.deserializeUser((obj: any, done: (err: any, id?: any) => void) => {
14  done(null, obj);
15});
16
17// Configure Google Strategy
18passport.use(new GoogleStrategy({
19    clientID: process.env.GOOGLE_CLIENT_ID as string,
20    clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
21    callbackURL: "http://localhost:3000/auth/google/callback"
22  },
23  (accessToken: string, refreshToken: string, profile: Profile, done: VerifyCallback) => {
24    // In a production app, you would look up or create a user in your database here
25    return done(null, profile);
26  }
27));
28
29// Middleware
30app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: true }));
31app.use(passport.initialize());
32app.use(passport.session());
33
34// Routes
35app.get('/auth/google',
36  passport.authenticate('google', { scope: ['profile', 'email'] })
37);
38
39app.get('/auth/google/callback', 
40  passport.authenticate('google', { failureRedirect: '/login' }),
41  (req: Request, res: Response) => {
42    // Successful authentication, redirect home.
43    res.redirect('/');
44  }
45);
46
47app.get('/', (req: Request, res: Response) => {
48  res.send(req.user ? `Hello ${ (req.user as Profile).displayName }` : 'Not logged in');
49});
50
51app.listen(3000, () => {
52  console.log('Server started on http://localhost:3000');
53});
express_passport_google_oauth2_authentication_with_session.ts - Raysurfer Public Snippets