Skip to content

Instantly share code, notes, and snippets.

@bvenkatr
Forked from fuxingloh/app.js
Created August 29, 2021 09:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bvenkatr/c81c65a5a0fb29eb7240594923e1eb27 to your computer and use it in GitHub Desktop.
Save bvenkatr/c81c65a5a0fb29eb7240594923e1eb27 to your computer and use it in GitHub Desktop.
How to use express.js and passport.js with G Suite SAML Apps SSO
const express = require('express')
const SamlStrategy = require('passport-saml').Strategy
const passport = require('passport')
const cookieSession = require('cookie-session')
const cookieParser = require('cookie-parser')
// Create express instance
const app = express()
// Configure your cookie session or alternatives
app.use(cookieParser())
app.use(cookieSession({
name: 'session',
keys: ['super secret'],
maxAge: 2 * 24 * 60 * 60 * 1000 // 2 days
}))
app.use(passport.initialize())
app.use(passport.session())
passport.use(new SamlStrategy({
protocol: 'https://',
entryPoint: 'https://accounts.google.com/o/saml2/idp?idpid=', // SSO URL (Step 2)
issuer: 'https://.../sp', // Entity ID (Step 4)
path: '/auth/saml/callback' // ACS URL path (Step 4)
}, function (profile, done) {
// Parse user profile data
done(null, {
email: profile.email,
name: profile.name
})
})
)
passport.serializeUser(function (user, done) {
done(null, user)
})
passport.deserializeUser(function (user, done) {
done(null, user)
})
app.get('/login', passport.authenticate('saml', {
successRedirect: '/',
failureRedirect: '/login'
}))
app.get('/logout', function (req, res) {
req.logout()
res.end('You have logged out.')
})
app.post('/auth/saml/callback', passport.authenticate('saml', {
failureRedirect: '/error',
failureFlash: true
}), function (req, res) {
res.redirect('/')
})
// Securing every path in production.
app.all('*', function (req, res, next) {
if (req.isAuthenticated() || process.env.NODE_ENV !== 'production') {
next()
} else {
res.redirect('/login')
}
})
# https://github.com/bergie/passport-saml
yarn add passport passport-saml
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment