How to use passport-saml - 10 common examples

To help you get started, we’ve selected a few passport-saml examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github rickbergfalk / sqlpad / server / middleware / passport.js View on Github external
new PassportGoogleStrategy(
      {
        clientID: googleClientId,
        clientSecret: googleClientSecret,
        callbackURL: publicUrl + baseUrl + '/auth/google/callback',
        // This option tells the strategy to use the userinfo endpoint instead
        userProfileURL: 'https://www.googleapis.com/oauth2/v3/userinfo?alt=json'
      },
      passportGoogleStrategyHandler
    )
  );
}

if (samlEntryPoint) {
  passport.use(
    new SamlStrategy(
      {
        path: '/login/callback',
        entryPoint: samlEntryPoint,
        issuer: samlIssuer,
        callbackUrl: samlCallbackUrl,
        cert: samlCert,
        authnContext: samlAuthContext,
        identifierFormat: null
      },
      async function(p, done) {
        const email =
          p[
            'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress'
          ];
        const user = await usersUtil.findOneByEmail(email);
        console.log(`User logged in with SAML as ${email}`);
github realestate-com-au / sshephalopod / lambda / Metadata.js View on Github external
requestIdExpirationPeriodMs: 3600000,
        cacheProvider: {}, // since we won't be sticking around ...
        forceAuthn: true,
        identifierFormat: "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified",
        decryptionPvk: fs.readFileSync("saml_sp.key").toString()
    };

    saml_options.callbackUrl =
        'https://' + event['api-id'] + '.execute-api.' + event.region + '.amazonaws.com/' +
        event.stage + event['resource-path'];

    console.log('callbackURL is ' + saml_options.callbackUrl);

    var certificate = fs.readFileSync("saml_sp.crt").toString();

    var saml = new SAML(saml_options);

    var metadata = saml.generateServiceProviderMetadata(certificate);

    console.log("Created metadata: %j", metadata);
    context.done(null, metadata);
};
github salesforce / refocus / view / loadView.js View on Github external
.then((ssoconfig) => {
        if (ssoconfig) {
          const redirectUrl = getRedirectUrlSSO(req);

          // add relay state to remember redirect url when a response is
          // returned from SAML IdP in post /sso/saml route
          passport.use(new SamlStrategy(
            {
              path: '/sso/saml',
              entryPoint: ssoconfig.samlEntryPoint,
              issuer: ssoconfig.samlIssuer,
              additionalParams: { RelayState: redirectUrl },
            }, samlAuthentication)
          );

          return next();
        }

        return res.status(httpStatus.NOT_FOUND).send('Page not found');
      })
      .catch(() => res.status(httpStatus.NOT_FOUND).send('Page not found'));
github ngageoint / mage-server / authentication / saml.js View on Github external
}

  function authorizeDevice(req, res, next) {
    provisioning.provision.check(provisioning.strategy, {uid: req.param('uid')}, function(err, device) {
      if (err) return next(err);

      if (provisioning.strategy === 'uid' && (!device || !device.registered)) {
        return res.sendStatus(403);
      } else {
        req.device = device;
        next();
      }
    })(req, res, next);
  }

  passport.use(new SamlStrategy(strategyConfig.options, function(profile, done) {
    const username = profile[strategyConfig.uidAttribute];
    User.getUserByAuthenticationId('saml', username, function(err, user) {
      if (err) return done(err);

      if (!user) {
        // Create an account for the user
        Role.getRole('USER_ROLE', function(err, role) {
          if (err) return done(err);

          var user = {
            username: username,
            displayName: profile[strategyConfig.displayNameAttribute],
            email: profile[strategyConfig.emailAttribute],
            active: false,
            roleId: role._id,
            authentication: {
github weseek / growi / src / server / service / passport.js View on Github external
// check whether the strategy has already been set up
    if (this.isSamlStrategySetup) {
      throw new Error('SamlStrategy has already been set up');
    }

    const { configManager } = this.crowi;
    const isSamlEnabled = configManager.getConfig('crowi', 'security:passport-saml:isEnabled');

    // when disabled
    if (!isSamlEnabled) {
      return;
    }

    debug('SamlStrategy: setting up..');
    passport.use(
      new SamlStrategy(
        {
          entryPoint: configManager.getConfig('crowi', 'security:passport-saml:entryPoint'),
          callbackUrl: (this.crowi.appService.getSiteUrl() != null)
            ? urljoin(this.crowi.appService.getSiteUrl(), '/passport/saml/callback') // auto-generated with v3.2.4 and above
            : configManager.getConfig('crowi', 'security:passport-saml:callbackUrl'), // DEPRECATED: backward compatible with v3.2.3 and below
          issuer: configManager.getConfig('crowi', 'security:passport-saml:issuer'),
          cert: configManager.getConfig('crowi', 'security:passport-saml:cert'),
        },
        (profile, done) => {
          if (profile) {
            return done(null, profile);
          }

          return done(null, false);
        },
      ),
github feup-infolab / dendro / src / bootup / models / shibboleth / shibboleth.js View on Github external
registerAuthenticationRoutes(app, passport)
    {
        const self = this;
        let saml = require("passport-saml");
        let samlStrategy = new saml.Strategy({
            // URL that goes from the Identity Provider -> Service Provider
            callbackUrl: self.getCallbackURl(),
            // URL that goes from the Service Provider -> Identity Provider
            entryPoint: self.getEntryPoint(),
            // Usually specified as `/shibboleth` from site root
            issuer: self.getIssuer(),
            identifierFormat: null,
            // Service Provider private key
            decryptionPvk: self.getKey(),
            // Service Provider Certificate
            privateCert: self.getKey(),
            // Identity Provider's public key
            cert: self.getIdpCert(),
            validateInResponseTo: false,
            disableRequestedAuthnContext: true
        }, function(profile, done) {
github ayr-ton / kamu / auth / passport.js View on Github external
firstName = username.split(' ')[0];
    lastName  = username.split(' ')[1];

    var user = { firstName: firstName, lastName: lastName, nameID: username.replace(/ /, '.').concat('@thoughtworks.com') };

    function byEmail(current) { return current.nameID == user.nameID; }

    if (users.filter(byEmail).length == 0) {
      users.push(user);
    }

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

passport.use(new SamlStrategy(
  {
    issuer: config.auth.issuer,
  	path: config.auth.path,
    entryPoint: config.auth.entryPoint,
    cert: config.auth.cert
  },
  function(profile, done) {
    if (!profile.nameID) {
      return done(new Error("No email found"), null);
    }
    process.nextTick(function () {
      findByEmail(profile.nameID, function(err, user) {
        if (err) {
          return done(err);
        }
        if (!user) {
github realestate-com-au / sshephalopod / lambda / SigningRequestPassport.js View on Github external
}, function AssertResponse(next) {
            var saml = new SAML(saml_options);

            console.log("Going to try and assert a response: %j", saml_options);

            var saml2_response = xpath.select(SAML2_RESPONSE_XPATH, saml_doc).toString();
            console.log('using saml2_response: %j', saml2_response);

            console.log("Retrieving real name from XML");
            realName = xpath.select(REALNAME_XPATH, saml_doc).toString();
            console.log("Got realName of " + realName);
            var encoded_response = new Buffer(saml2_response).toString('base64');
            var response = {
                SAMLResponse: encoded_response
            };
            saml.validatePostResponse(response, next);
        },
        function checkLoggedOut(profile, loggedOut, next) {
github avoidwork / tenso / lib / tenso.es6.js View on Github external
(function () {
			let arg = config.auth.saml;

			arg.callbackURL = realm + "/auth/saml/callback";
			delete arg.enabled;
			delete arg.path;

			passport.use(new SAMLStrategy(arg, function (profile, done) {
				config.auth.saml.auth(profile, function (err, user) {
					if (err) {
						delete err.stack;
						return done(err);
					}

					done(null, user);
				});
			}));
		}());
github partio-scout / reki / src / server / boot / 03-partioid-login.js View on Github external
export default function(app) {
  const rekiBaseUrl = new URL(process.env.REKI_BASE_URL || 'http://localhost:3000');

  const useProductionPartioID = process.env.PARTIOID_USE_PRODUCTION === 'true';
  const partioIDRemoteName = useProductionPartioID ? 'id' : 'partioid-test';
  const partioIdIssuer = rekiBaseUrl.href;
  const partioIdEntryPoint = `https://${partioIDRemoteName}.partio.fi/simplesaml/saml2/idp/SSOService.php`;
  const partioIdLogoutUrl = `https://${partioIDRemoteName}.partio.fi/simplesaml/saml2/idp/SingleLogoutService.php`;
  const partioIdCertificate = fs.readFileSync(path.resolve(`./certs/partioid/${partioIDRemoteName}.crt`), 'utf-8');

  const strategy =  new SamlStrategy(
    {
      callback: new URL('/saml/consume', rekiBaseUrl).href,
      issuer: partioIdIssuer,
      entryPoint: partioIdEntryPoint,
      cert: partioIdCertificate,
      logoutUrl: partioIdLogoutUrl,
      logoutCallbackUrl: 'http://localhost:3000/saml/consume-logout',
      identifierFormat: 'urn:oasis:names:tc:SAML:1.1:nameid-format:transient',
    },
    async (profile, done) => {
      try {
        if (!profile || !profile.membernumber) {
          done(null, false, { message: 'Jäsennumero puuttuu PartioID-vastauksesta.' });
          return;
        }

passport-saml

SAML 2.0 authentication strategy for Passport

MIT
Latest version published 2 years ago

Package Health Score

53 / 100
Full package analysis