Skip to content

Commit 4a4ae9d

Browse files
committed
Initial support for SAML authentication
1 parent 9c002ce commit 4a4ae9d

File tree

12 files changed

+157
-4
lines changed

12 files changed

+157
-4
lines changed

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,8 @@ There are some configs you need to change in the files below
172172
| HMD_LDAP_SEARCHATTRIBUTES | no example | LDAP attributes to search with |
173173
| HMD_LDAP_TLS_CA | `server-cert.pem, root.pem` | Root CA for LDAP TLS in PEM format (use comma to separate) |
174174
| HMD_LDAP_PROVIDERNAME | `My institution` | Optional name to be displayed at login form indicating the LDAP provider |
175+
| HMD_SAML_IDPSSOURL | `https://idp.example.com/sso` | authentication endpoint of IdP |
176+
| HMD_SAML_IDPCERT | `/path/to/cert.pem` | certificate file path of IdP in PEM format |
175177
| HMD_IMGUR_CLIENTID | no example | Imgur API client id |
176178
| HMD_EMAIL | `true` or `false` | set to allow email signin |
177179
| HMD_ALLOW_PDF_EXPORT | `true` or `false` | Enable or disable PDF exports |
@@ -234,7 +236,7 @@ There are some configs you need to change in the files below
234236

235237
| service | settings location | description |
236238
| ------- | --------- | ----------- |
237-
| facebook, twitter, github, gitlab, mattermost, dropbox, google, ldap | environment variables or `config.json` | for signin |
239+
| facebook, twitter, github, gitlab, mattermost, dropbox, google, ldap, saml | environment variables or `config.json` | for signin |
238240
| imgur, s3 | environment variables or `config.json` | for image upload |
239241
| google drive(`google/apiKey`, `google/clientID`), dropbox(`dropbox/appKey`) | `config.json` | for export and import |
240242

config.json.example

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,22 @@
7575
"changeme": "See https://nodejs.org/api/tls.html#tls_tls_connect_options_callback"
7676
}
7777
},
78+
"saml": {
79+
"idpSsoUrl": "change: authentication endpoint of IdP",
80+
"idpCert": "change: certificate file path of IdP in PEM format",
81+
"issuer": "change or delete: identity of the service provider (default: serverurl)",
82+
"callbackUrl": "change or delete: callback url to consume assertions (default: serverurl+'/auth/saml/callback')",
83+
"identifierFormat": "change or delete: name identifier format (default: 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress')",
84+
"groupAttribute": "change or delete: attribute name for group list (ex: memberOf)",
85+
"requiredGroups": [ "change or delete: group names that allowed" ],
86+
"externalGroups": [ "change or delete: group names that not allowed" ],
87+
"attribute": {
88+
"id": "change or delete this: attribute map for `id` (default: NameID)",
89+
"username": "change or delete this: attribute map for `username` (default: NameID)",
90+
"displayName": "change or delete this: attribute map for `displayName` (default: NameID)",
91+
"email": "change or delete this: attribute map for `email` (default: NameID)"
92+
}
93+
},
7894
"imgur": {
7995
"clientID": "change this"
8096
},

lib/config/default.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,22 @@ module.exports = {
9898
searchAttributes: undefined,
9999
tlsca: undefined
100100
},
101+
saml: {
102+
idpSsoUrl: undefined,
103+
idpCert: undefined,
104+
issuer: undefined,
105+
callbackUrl: undefined,
106+
identifierFormat: 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress',
107+
groupAttribute: undefined,
108+
externalGroups: [],
109+
requiredGroups: [],
110+
attribute: {
111+
id: undefined,
112+
username: undefined,
113+
displayName: undefined,
114+
email: undefined
115+
}
116+
},
101117
email: true,
102118
allowemailregister: true,
103119
allowpdfexport: true

lib/config/environment.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,10 @@ module.exports = {
7373
searchAttributes: process.env.HMD_LDAP_SEARCHATTRIBUTES,
7474
tlsca: process.env.HMD_LDAP_TLS_CA
7575
},
76+
saml: {
77+
idpSsoUrl: process.env.HMD_SAML_IDPSSOURL,
78+
idpCert: process.env.HMD_SAML_IDPCERT
79+
},
7680
email: toBooleanConfig(process.env.HMD_EMAIL),
7781
allowemailregister: toBooleanConfig(process.env.HMD_ALLOW_EMAIL_REGISTER),
7882
allowpdfexport: toBooleanConfig(process.env.HMD_ALLOW_PDF_EXPORT)

lib/config/index.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ config.isGitHubEnable = config.github.clientID && config.github.clientSecret
9292
config.isGitLabEnable = config.gitlab.clientID && config.gitlab.clientSecret
9393
config.isMattermostEnable = config.mattermost.clientID && config.mattermost.clientSecret
9494
config.isLDAPEnable = config.ldap.url
95+
config.isSAMLEnable = config.saml.idpSsoUrl
9596
config.isPDFExportEnable = config.allowpdfexport
9697

9798
// generate correct path

lib/models/user.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,15 @@ module.exports = function (sequelize, DataTypes) {
143143
photo = letterAvatars(profile.username)
144144
}
145145
break
146+
case 'saml':
147+
if (profile.emails[0]) {
148+
photo = 'https://www.gravatar.com/avatar/' + md5(profile.emails[0])
149+
if (bigger) photo += '?s=400'
150+
else photo += '?s=96'
151+
} else {
152+
photo = letterAvatars(profile.username)
153+
}
154+
break
146155
}
147156
return photo
148157
},

lib/response.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ function showIndex (req, res, next) {
6868
dropbox: config.isDropboxEnable,
6969
google: config.isGoogleEnable,
7070
ldap: config.isLDAPEnable,
71+
saml: config.isSAMLEnable,
7172
email: config.isEmailEnable,
7273
allowemailregister: config.allowemailregister,
7374
allowpdfexport: config.allowpdfexport,
@@ -100,6 +101,7 @@ function responseHackMD (res, note) {
100101
dropbox: config.isDropboxEnable,
101102
google: config.isGoogleEnable,
102103
ldap: config.isLDAPEnable,
104+
saml: config.isSAMLEnable,
103105
email: config.isEmailEnable,
104106
allowemailregister: config.allowemailregister,
105107
allowpdfexport: config.allowpdfexport

lib/web/auth/index.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ if (config.isMattermostEnable) authRouter.use(require('./mattermost'))
3737
if (config.isDropboxEnable) authRouter.use(require('./dropbox'))
3838
if (config.isGoogleEnable) authRouter.use(require('./google'))
3939
if (config.isLDAPEnable) authRouter.use(require('./ldap'))
40+
if (config.isSAMLEnable) authRouter.use(require('./saml'))
4041
if (config.isEmailEnable) authRouter.use(require('./email'))
4142

4243
// logout

lib/web/auth/saml/index.js

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
'use strict'
2+
3+
const Router = require('express').Router
4+
const passport = require('passport')
5+
const SamlStrategy = require('passport-saml').Strategy
6+
const config = require('../../../config')
7+
const models = require('../../../models')
8+
const logger = require('../../../logger')
9+
const {urlencodedParser} = require('../../utils')
10+
const fs = require('fs')
11+
const intersection = function (array1, array2) { return array1.filter((n) => array2.includes(n)) }
12+
13+
let samlAuth = module.exports = Router()
14+
15+
passport.use(new SamlStrategy({
16+
callbackUrl: config.saml.callbackUrl || config.serverurl + '/auth/saml/callback',
17+
entryPoint: config.saml.idpSsoUrl,
18+
issuer: config.saml.issuer || config.serverurl,
19+
cert: fs.readFileSync(config.saml.idpCert, 'utf-8'),
20+
identifierFormat: config.saml.identifierFormat
21+
}, function (user, done) {
22+
// check authorization if needed
23+
if (config.saml.externalGroups && config.saml.grouptAttribute) {
24+
var externalGroups = intersection(config.saml.externalGroups, user[config.saml.groupAttribute])
25+
if (externalGroups.length > 0) {
26+
logger.error('saml permission denied: ' + externalGroups.join(', '))
27+
return done('Permission denied', null)
28+
}
29+
}
30+
if (config.saml.requiredGroups && config.saml.grouptAttribute) {
31+
if (intersection(config.saml.requiredGroups, user[config.saml.groupAttribute]).length === 0) {
32+
logger.error('saml permission denied')
33+
return done('Permission denied', null)
34+
}
35+
}
36+
// user creation
37+
var uuid = user[config.saml.attribute.id] || user.nameID
38+
var profile = {
39+
provider: 'saml',
40+
id: 'SAML-' + uuid,
41+
username: user[config.saml.attribute.username] || user.nameID,
42+
displayName: user[config.saml.attribute.displayName] || user.nameID,
43+
emails: user[config.saml.attribute.email] ? [user[config.saml.attribute.email]] : []
44+
}
45+
if (profile.emails.length === 0 && config.saml.identifierFormat === 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress') {
46+
profile.emails.push(user.nameID)
47+
}
48+
var stringifiedProfile = JSON.stringify(profile)
49+
models.User.findOrCreate({
50+
where: {
51+
profileid: profile.id.toString()
52+
},
53+
defaults: {
54+
profile: stringifiedProfile
55+
}
56+
}).spread(function (user, created) {
57+
if (user) {
58+
var needSave = false
59+
if (user.profile !== stringifiedProfile) {
60+
user.profile = stringifiedProfile
61+
needSave = true
62+
}
63+
if (needSave) {
64+
user.save().then(function () {
65+
if (config.debug) { logger.debug('user login: ' + user.id) }
66+
return done(null, user)
67+
})
68+
} else {
69+
if (config.debug) { logger.debug('user login: ' + user.id) }
70+
return done(null, user)
71+
}
72+
}
73+
}).catch(function (err) {
74+
logger.error('saml auth failed: ' + err)
75+
return done(err, null)
76+
})
77+
}))
78+
79+
samlAuth.get('/auth/saml',
80+
passport.authenticate('saml', {
81+
successReturnToOrRedirect: config.serverurl + '/',
82+
failureRedirect: config.serverurl + '/'
83+
})
84+
)
85+
86+
samlAuth.post('/auth/saml/callback', urlencodedParser,
87+
passport.authenticate('saml', {
88+
successReturnToOrRedirect: config.serverurl + '/',
89+
failureRedirect: config.serverurl + '/'
90+
})
91+
)
92+
93+
samlAuth.get('/auth/saml/metadata', function (req, res) {
94+
res.type('application/xml')
95+
res.send(passport._strategy('saml').generateServiceProviderMetadata())
96+
})

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@
9494
"passport-local": "^1.0.0",
9595
"passport-oauth2": "^1.4.0",
9696
"passport-twitter": "^1.0.4",
97+
"passport-saml": "^0.31.0",
9798
"passport.socketio": "^3.7.0",
9899
"pdfobject": "^2.0.201604172",
99100
"pg": "^6.1.2",

0 commit comments

Comments
 (0)