How to use openid-client - 10 common examples

To help you get started, we’ve selected a few openid-client 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 linksmart / border-gateway / bgw-auth-service / config.js View on Github external
console.log("Could not retrieve oidc configuration for oidc provider " + providerKey);
            process.exit(1);
        } else {

            if(!response.data || !response.data.issuer || !response.data.token_endpoint || !response.data.authorization_endpoint || !response.data.jwks_uri)
            {
                console.log("Response from oidc provider does not contain expected values " + response);
                process.exit(1);
            }

            provider.issuer = response.data.issuer;
            provider.token_endpoint = response.data.token_endpoint;
            provider.authorization_endpoint = response.data.authorization_endpoint;
            provider.jwks_uri = response.data.jwks_uri;

            let issuer = new Issuer({
                issuer: provider.issuer,
                authorization_endpoint: provider.authorization_endpoint,
                token_endpoint: provider.token_endpoint,
                jwks_uri: provider.jwks_uri
            }); // => Issuer
            console.log('Set up issuer %s %O', issuer.issuer, issuer.metadata);

            provider.client = new issuer.Client({
                client_id: provider.client_id,
                client_secret: provider.client_secret
            });


            axios({
                method: 'get',
                url: provider.jwks_uri,
github repl-it-discord / carnival / experiment / central-server / index.js View on Github external
resave: true,
    saveUninitialized: false
  })
);

app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname + "/public/index.html"));
});

// Auth
let { Issuer, Strategy } = require("openid-client");

// Create issuer representing delegated authorization server
let theURL;
let theClient;
Issuer.discover("http://localhost:3100") // => Promise
  .then(issuer => {
    console.log("Discovered issuer %s %O", issuer.issuer, issuer.metadata);
    console.log("[Client] OIDC Server Found");

    // TODO: Cleanup
    // Setup client stuff
    const client = new issuer.Client({
      client_id: "RST",
      client_secret: "RomeoSierraTango",

      grant_types: ["authorization_code"],
      response_types: ["code"],
      token_endpoint_auth_method: "none",
      id_token_signed_response_alg: "RS256",
      token_endpoint_auth_method: "client_secret_basic"
    }); // => Client
github onelogin / onelogin-oidc-node / 5. Auth Flow - PKCE / app.js View on Github external
});

    const params = {
      client_id: process.env.OIDC_CLIENT_ID,
      redirect_uri: process.env.OIDC_REDIRECT_URI,
      scope: 'openid profile',
    }

    const passReqToCallback = false; // optional, defaults to false, when true req is passed as a first
                                     // argument to verify fn

    const usePKCE = 'S256'; // optional, defaults to false, when true the code_challenge_method will be
                          // resolved from the issuer configuration, instead of true you may provide
                          // any of the supported values directly, i.e. "S256" (recommended) or "plain"

    passport.use('oidc', new Strategy({ client, params, passReqToCallback, usePKCE }, (tokenset, userinfo, done) => {
      console.log('tokenset', tokenset);
      console.log('access_token', tokenset.access_token);
      console.log('id_token', tokenset.id_token);
      console.log('claims', tokenset.claims);
      console.log('userinfo', userinfo);

      return done(null, userinfo)
    }));
  });
github ngageoint / mage-server / authentication / login-gov.js View on Github external
]).then(function([keystore, issuer]) {
    loginGov.issuer = issuer; // allow subsequent access to issuer.end_session_endpoint (required during RP-Initiated Logout)

    client = new issuer.Client({
      client_id: strategyConfig.client_id,
      token_endpoint_auth_method: 'private_key_jwt',
      id_token_signed_response_alg: 'RS256'
    }, keystore);

    client.CLOCK_TOLERANCE = 10;

    var params = getParams();
    passport.use('oidc-loa-1', new Strategy({client: client, params: params, passReqToCallback: true}, function(req, tokenset, userinfo, done) {
      userinfo.token = tokenset.id_token; // required for RP-Initiated Logout
      userinfo.state = params.state; // required for RP-Initiated Logout

      User.getUserByAuthenticationId('login-gov', userinfo.email, function(err, user) {
        if (err) return done(err);

        var email = userinfo.email;

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

            var user = {
              username: email,
              displayName: email.split("@")[0],
github weseek / growi / src / server / service / passport.js View on Github external
if (!isOidcEnabled) {
      return;
    }

    debug('OidcStrategy: setting up..');

    // setup client
    // extend oidc request timeouts
    OIDCIssuer.defaultHttpOptions = { timeout: 5000 };
    const issuerHost = configManager.getConfig('crowi', 'security:passport-oidc:issuerHost');
    const clientId = configManager.getConfig('crowi', 'security:passport-oidc:clientId');
    const clientSecret = configManager.getConfig('crowi', 'security:passport-oidc:clientSecret');
    const redirectUri = (configManager.getConfig('crowi', 'app:siteUrl') != null)
      ? urljoin(this.crowi.appService.getSiteUrl(), '/passport/oidc/callback')
      : configManager.getConfig('crowi', 'security:passport-oidc:callbackUrl'); // DEPRECATED: backward compatible with v3.2.3 and below
    const oidcIssuer = await OIDCIssuer.discover(issuerHost);
    debug('Discovered issuer %s %O', oidcIssuer.issuer, oidcIssuer.metadata);

    const client = new oidcIssuer.Client({
      client_id: clientId,
      client_secret: clientSecret,
      redirect_uris: [redirectUri],
      response_types: ['code'],
    });

    passport.use('oidc', new OidcStrategy({
      client,
      params: { scope: 'openid email profile' },
    },
    ((tokenset, userinfo, done) => {
      if (userinfo) {
        return done(null, userinfo);
github stelace / stelace / src / services / authentication.js View on Github external
if (protocol === 'openid') {
    if (endSessionUrl) {
      issuerParams.end_session_endpoint = endSessionUrl
    }
    if (jwks || jwksUrl) {
      issuerParams.jwks_uri = jwksUrl || getJwksUrl({ publicPlatformId, provider, serverPort })
    }
    if (idTokenSignedResponseAlg) { // node-openid-client default: 'RS256'
      issuerParams.id_token_signed_response_alg = idTokenSignedResponseAlg
    }
    if (tokenEndpointAuthSigningAlg) {
      issuerParams.token_endpoint_auth_signing_alg = tokenEndpointAuthSigningAlg
    }
  }

  const issuer = new Issuer(issuerParams)

  const client = new issuer.Client({
    client_id: clientId,
    client_secret: clientSecret || null,
    response_types: ['code']
  })

  return client
}
github keattang / eks-auth-proxy / src / oidc.js View on Github external
const getPassportStrategy = async () => {
    if (passportStrategy !== undefined) {
        return Promise.resolve(passportStrategy);
    }

    const client = await getClient();

    const params = { scope: 'openid email' };
    const usePKCE = true; // optional, defaults to false, when true the code_challenge_method will be
    // resolved from the issuer configuration, instead of true you may provide
    // any of the supported values directly, i.e. "S256" (recommended) or "plain"

    passportStrategy = new Strategy(
        { client, params, usePKCE },
        handleAuthenticationSuccess
    );

    return passportStrategy;
};
github havfo / multiparty-meeting / server / server.js View on Github external
// client_id defaults to client.client_id
	// redirect_uri defaults to client.redirect_uris[0]
	// response type defaults to client.response_types[0], then 'code'
	// scope defaults to 'openid'
	const params = auth.clientOptions;
	
	// optional, defaults to false, when true req is passed as a first
	// argument to verify fn
	const passReqToCallback = false;
	
	// optional, defaults to false, when true the code_challenge_method will be
	// resolved from the issuer configuration, instead of true you may provide
	// any of the supported values directly, i.e. "S256" (recommended) or "plain"
	const usePKCE = false;

	oidcStrategy = new Strategy(
		{ client: oidcClient, params, passReqToCallback, usePKCE },
		(tokenset, userinfo, done) =>
		{
			const user =
			{
				id        : tokenset.claims.sub,
				provider  : tokenset.claims.iss,
				_userinfo : userinfo,
				_claims   : tokenset.claims
			};

			if (userinfo.picture != null)
			{
				if (!userinfo.picture.match(/^http/g))
				{
					user.picture = `data:image/jpeg;base64, ${userinfo.picture}`;
github weseek / growi / src / server / service / passport.js View on Github external
const clientId = configManager.getConfig('crowi', 'security:passport-oidc:clientId');
    const clientSecret = configManager.getConfig('crowi', 'security:passport-oidc:clientSecret');
    const redirectUri = (configManager.getConfig('crowi', 'app:siteUrl') != null)
      ? urljoin(this.crowi.appService.getSiteUrl(), '/passport/oidc/callback')
      : configManager.getConfig('crowi', 'security:passport-oidc:callbackUrl'); // DEPRECATED: backward compatible with v3.2.3 and below
    const oidcIssuer = await OIDCIssuer.discover(issuerHost);
    debug('Discovered issuer %s %O', oidcIssuer.issuer, oidcIssuer.metadata);

    const client = new oidcIssuer.Client({
      client_id: clientId,
      client_secret: clientSecret,
      redirect_uris: [redirectUri],
      response_types: ['code'],
    });

    passport.use('oidc', new OidcStrategy({
      client,
      params: { scope: 'openid email profile' },
    },
    ((tokenset, userinfo, done) => {
      if (userinfo) {
        return done(null, userinfo);
      }

      return done(null, false);

    })));

    this.isOidcStrategySetup = true;
    debug('OidcStrategy: setup is done');
  }
github DFEAGILEDEVOPS / MTC / admin / authentication / dfe-signin-strategy.js View on Github external
.then((issuer) => {
      logger.info('dfe sign on discovered successfully')
      const client = new issuer.Client({
        client_id: config.Auth.dfeSignIn.clientId,
        client_secret: config.Auth.dfeSignIn.clientSecret
      })
      if (config.Auth.dfeSignIn.clockToleranceSeconds && config.Auth.dfeSignIn.clockToleranceSeconds > 0) {
        client.CLOCK_TOLERANCE = config.Auth.dfeSignIn.clockToleranceSeconds
      }
      const dfeStrategy = new Strategy({
        client,
        params: {
          scope: config.Auth.dfeSignIn.openIdScope
        }
      }, async (tokenset, authUserInfo, done) => {
        try {
          // authUserInfo appears to be exactly the same as what client.userinfo returns 🤷‍♂️
          // let userInfo = await client.userinfo(tokenset.access_token)
          const userInfo = await dfeSigninService.initialiseUser(authUserInfo, tokenset)
          done(null, userInfo)
        } catch (error) {
          logger.error(error)
          done(error)
        }
      })
      passport.use(authModes.dfeSignIn, dfeStrategy)