Valid to call only for /management endpoints, not valid for SSO to Keycloak
187741
void onConnect(BootstrapServer server) {
        // store selected server
        new BootstrapServerStore().storeSelection(server);

        if (dialog != null) {
            dialog.hide();
            LoadingPanel.get().on();
        }
        String serverUrl = getServerUrl(server);
        context.setSameOrigin(serverUrl.equals(getBaseUrl()));
        if (!serverUrl.endsWith("/")) {
            serverUrl += "/";
        }

        // Trigger authentication using a hidden iframe. This way also Safari will show the login dialog
        setUrls(serverUrl);
        andThen.execute();
    }
995208
function loadEndpoints(endpoints, options, auth) {
	if (Array.isArray(endpoints)) {
		endpoints.forEach(function(endpoint) {
			if (auth !== Boolean(endpoint.authenticated)) {
				//after endpoints refactored, remove this check
				return;
			}
			const conditional = endpoint.hasOwnProperty("ifProp");
			if (conditional && options.configParams.get(endpoint.ifProp) || !conditional) {
				tryLoadRouter(endpoint, options);
			}
		});
	}
}
1251476
function (privmsg, adminOnlyCallback) {
            // If the "command" property is set, it's a command, and not a privmsg.
            // The prototype of a command is the privmsg though.
            const memoizeOver = privmsg.command ? Object.getPrototypeOf(privmsg) : privmsg;
            const allowAll = privmsg[allowAllSymbol];

            return isAdmin(privmsg.hostmask, {memoizeOver, allowAll})
            .then(function (isAdmin) {
                if (isAdmin) {
                    return adminOnlyCallback();
                } else {
                    client.note("PluginAdmin", format("'%s' tried to execute admin-only functionality", privmsg.nickname));
                    return deniedResponse;
                }
            });
        }
831261
def gitlab_endpoint_exists?(gitlab_url)
      with_gitlab(gitlab_url, 'Iamsecret') do |g|
        g.user
      end
    rescue Gitlab::Error::Unauthorized
      true
    rescue Exception
      false
    end
1237323
@CliObjectOption(description = "Authenticate using kerberos. Format: \"<login-user>:<keytab-file>\".")
  public EmbeddedGobblin kerberosAuthentication(String credentials) {
    List<String> split = Splitter.on(":").splitToList(credentials);
    if (split.size() != 2) {
      throw new RuntimeException("Cannot parse " + credentials + ". Expected <login-user>:<keytab-file>");
    }
    try {
      usePlugin(PluginStaticKeys.HADOOP_LOGIN_FROM_KEYTAB_ALIAS);
    } catch (ReflectiveOperationException roe) {
      throw new RuntimeException(String.format("Could not instantiate %s. Make sure gobblin-runtime-hadoop is in your classpath.",
          PluginStaticKeys.HADOOP_LOGIN_FROM_KEYTAB_ALIAS), roe);
    }
    sysConfig(PluginStaticKeys.LOGIN_USER_FULL_KEY, split.get(0));
    sysConfig(PluginStaticKeys.LOGIN_USER_KEYTAB_FILE_FULL_KEY, split.get(1));
    return this;
  }
48655
def _validate_signature(self, request, principal, args, params):
        """"""
        creds = AWSCredentials(principal.access_key, principal.secret_key)
        endpoint = AWSServiceEndpoint()
        endpoint.set_method(request.method)
        endpoint.set_canonical_host(request.getHeader("Host"))
        path = request.path
        if self.path is not None:
            path = "%s/%s" % (self.path.rstrip("/"), path.lstrip("/"))
        endpoint.set_path(path)
        signature = Signature(creds, endpoint, params,
                              signature_method=args["signature_method"],
                              signature_version=args["signature_version"]
                              )
        if signature.compute() != args["signature"]:
            raise APIError(403, "SignatureDoesNotMatch",
                           "The request signature we calculated does not "
                           "match the signature you provided. Check your "
                           "key and signing method.")
651820
protected String getKeycloakUsername(final HttpServletRequest req, HttpServletResponse resp) {
        AtomicReference<String> username = new AtomicReference<>();
        Authenticator.authenticate(
            authConfiguration, req,
            subject -> {
                username.set(AuthHelpers.getUsername(subject));

                // Start httpSession
                req.getSession(true);
            }
        );
        return username.get();
    }
1189633
function isOcspValidationDisabled(host)
{
  // ocsp is disabled if insecure-connect is enabled, or if we've disabled ocsp
  // for non-snowflake endpoints and the host is a non-snowflake endpoint
  return GlobalConfig.isInsecureConnect() || (Parameters.getValue(
          Parameters.names.JS_DRIVER_DISABLE_OCSP_FOR_NON_SF_ENDPOINTS) &&
      !REGEX_SNOWFLAKE_ENDPOINT.test(host));
}
45440
def provider_parser(subparser):
    """"""
    subparser.add_argument("--auth-access-key",
                           help="specify ACCESS_KEY for authentication")
    subparser.add_argument("--auth-access-secret",
                           help="specify ACCESS_SECRET for authentication")
    subparser.add_argument(
        "--private-zone",
        help=("indicates what kind of hosted zone to use. If true, use "
              "only private zones. If false, use only public zones"))

    # TODO: these are only required for testing, we should figure out
    # a way to remove them & update the integration tests
    # to dynamically populate the auth credentials that are required.
    subparser.add_argument(
        "--auth-username", help="alternative way to specify the ACCESS_KEY for authentication")
    subparser.add_argument(
        "--auth-token", help="alternative way to specify the ACCESS_SECRET for authentication")
1310696
def endpoint_catalog(catalog=None):  # noqa: E501
    
    if connexion.request.is_json:
        catalog = UserAuth.from_dict(connexion.request.get_json())  # noqa: E501
    return 'do some magic!'
108230
def key_required(group=None, perm=None, keytype=None):
    
    def decorator(f):
        def wrapper(request, *args, **kwargs):
            try:
                validate_key( request, group, perm, keytype )
                return f(request, *args, **kwargs)
            except AccessUnauthorized:
                return HttpResponse401( request )
            except AccessForbidden:
                return HttpResponse403( request )
        return wrapper 
    return decorator
951654
private SSLSocketFactory defaultSslSocketFactory(X509TrustManager trustManager)
      throws NoSuchAlgorithmException, KeyManagementException {
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[] { trustManager }, null);

    return sslContext.getSocketFactory();
  }
1268674
private void serverHelloDone(ServerHelloDone mesg) throws IOException {
        if (debug != null && Debug.isOn("handshake")) {
            mesg.print(System.out);
        }
        /*
         * Always make sure the input has been digested before we
         * start emitting data, to ensure the hashes are correctly
         * computed for the Finished and CertificateVerify messages
         * which we send (here).
         */
        input.digestNow();

        /*
         * FIRST ... if requested, send an appropriate Certificate chain
         * to authenticate the client, and remember the associated private
         * key to sign the CertificateVerify message.
         */
        PrivateKey signingKey = null;

        if (certRequest != null) {
            X509ExtendedKeyManager km = sslContext.getX509KeyManager();

            ArrayList<String> keytypesTmp = new ArrayList<>(4);

            for (int i = 0; i < certRequest.types.length; i++) {
                String typeName;

                switch (certRequest.types[i]) {
                case CertificateRequest.cct_rsa_sign:
                    typeName = "RSA";
                    break;

                case CertificateRequest.cct_dss_sign:
                    typeName = "DSA";
                    break;

                case CertificateRequest.cct_ecdsa_sign:
                    // ignore if we do not have EC crypto available
                    typeName = JsseJce.isEcAvailable() ? "EC" : null;
                    break;

                // Fixed DH/ECDH client authentication not supported
                case CertificateRequest.cct_rsa_fixed_dh:
                case CertificateRequest.cct_dss_fixed_dh:
                case CertificateRequest.cct_rsa_fixed_ecdh:
                case CertificateRequest.cct_ecdsa_fixed_ecdh:
                // Any other values (currently not used in TLS)
                case CertificateRequest.cct_rsa_ephemeral_dh:
                case CertificateRequest.cct_dss_ephemeral_dh:
                default:
                    typeName = null;
                    break;
                }

                if ((typeName != null) && (!keytypesTmp.contains(typeName))) {
                    keytypesTmp.add(typeName);
                }
            }

            String alias = null;
            int keytypesTmpSize = keytypesTmp.size();
            if (keytypesTmpSize != 0) {
                String keytypes[] =
                        keytypesTmp.toArray(new String[keytypesTmpSize]);

                if (conn != null) {
                    alias = km.chooseClientAlias(keytypes,
                        certRequest.getAuthorities(), conn);
                } else {
                    alias = km.chooseEngineClientAlias(keytypes,
                        certRequest.getAuthorities(), engine);
                }
            }

            CertificateMsg m1 = null;
            if (alias != null) {
                X509Certificate[] certs = km.getCertificateChain(alias);
                if ((certs != null) && (certs.length != 0)) {
                    PublicKey publicKey = certs[0].getPublicKey();
                    // for EC, make sure we use a supported named curve
                    if (publicKey instanceof ECPublicKey) {
                        ECParameterSpec params =
                            ((ECPublicKey)publicKey).getParams();
                        int index =
                            SupportedEllipticCurvesExtension.getCurveIndex(
                                params);
                        if (!SupportedEllipticCurvesExtension.isSupported(
                                index)) {
                            publicKey = null;
                        }
                    }
                    if (publicKey != null) {
                        m1 = new CertificateMsg(certs);
                        signingKey = km.getPrivateKey(alias);
                        session.setLocalPrivateKey(signingKey);
                        session.setLocalCertificates(certs);
                    }
                }
            }
            if (m1 == null) {
                //
                // No appropriate cert was found ... report this to the
                // server.  For SSLv3, send the no_certificate alert;
                // TLS uses an empty cert chain instead.
                //
                if (protocolVersion.v >= ProtocolVersion.TLS10.v) {
                    m1 = new CertificateMsg(new X509Certificate [0]);
                } else {
                    warningSE(Alerts.alert_no_certificate);
                }
            }

            //
            // At last ... send any client certificate chain.
            //
            if (m1 != null) {
                if (debug != null && Debug.isOn("handshake")) {
                    m1.print(System.out);
                }
                m1.write(output);
            }
        }

        /*
         * SECOND ... send the client key exchange message.  The
         * procedure used is a function of the cipher suite selected;
         * one is always needed.
         */
        HandshakeMessage m2;

        switch (keyExchange) {

        case K_RSA:
        case K_RSA_EXPORT:
            if (serverKey == null) {
                throw new SSLProtocolException
                        ("Server did not send certificate message");
            }

            if (!(serverKey instanceof RSAPublicKey)) {
                throw new SSLProtocolException
                        ("Server certificate does not include an RSA key");
            }

            /*
             * For RSA key exchange, we randomly generate a new
             * pre-master secret and encrypt it with the server's
             * public key.  Then we save that pre-master secret
             * so that we can calculate the keying data later;
             * it's a performance speedup not to do that until
             * the client's waiting for the server response, but
             * more of a speedup for the D-H case.
             *
             * If the RSA_EXPORT scheme is active, when the public
             * key in the server certificate is less than or equal
             * to 512 bits in length, use the cert's public key,
             * otherwise, the ephemeral one.
             */
            PublicKey key;
            if (keyExchange == K_RSA) {
                key = serverKey;
            } else {    // K_RSA_EXPORT
                if (JsseJce.getRSAKeyLength(serverKey) <= 512) {
                    // extraneous ephemeralServerKey check done
                    // above in processMessage()
                    key = serverKey;
                } else {
                    if (ephemeralServerKey == null) {
                        throw new SSLProtocolException("Server did not send" +
                            " a RSA_EXPORT Server Key Exchange message");
                    }
                    key = ephemeralServerKey;
                }
            }

            m2 = new RSAClientKeyExchange(protocolVersion, maxProtocolVersion,
                                sslContext.getSecureRandom(), key);
            break;
        case K_DH_RSA:
        case K_DH_DSS:
            /*
             * For DH Key exchange, we only need to make sure the server
             * knows our public key, so we calculate the same pre-master
             * secret.
             *
             * For certs that had DH keys in them, we send an empty
             * handshake message (no key) ... we flag this case by
             * passing a null "dhPublic" value.
             *
             * Otherwise we send ephemeral DH keys, unsigned.
             */
            // if (useDH_RSA || useDH_DSS)
            m2 = new DHClientKeyExchange();
            break;
        case K_DHE_RSA:
        case K_DHE_DSS:
        case K_DH_ANON:
            if (dh == null) {
                throw new SSLProtocolException
                    ("Server did not send a DH Server Key Exchange message");
            }
            m2 = new DHClientKeyExchange(dh.getPublicKey());
            break;
        case K_ECDHE_RSA:
        case K_ECDHE_ECDSA:
        case K_ECDH_ANON:
            if (ecdh == null) {
                throw new SSLProtocolException
                    ("Server did not send a ECDH Server Key Exchange message");
            }
            m2 = new ECDHClientKeyExchange(ecdh.getPublicKey());
            break;
        case K_ECDH_RSA:
        case K_ECDH_ECDSA:
            if (serverKey == null) {
                throw new SSLProtocolException
                        ("Server did not send certificate message");
            }
            if (serverKey instanceof ECPublicKey == false) {
                throw new SSLProtocolException
                        ("Server certificate does not include an EC key");
            }
            ECParameterSpec params = ((ECPublicKey)serverKey).getParams();
            ecdh = new ECDHCrypt(params, sslContext.getSecureRandom());
            m2 = new ECDHClientKeyExchange(ecdh.getPublicKey());
            break;
        case K_KRB5:
        case K_KRB5_EXPORT:
            String hostname = getHostSE();
            if (hostname == null) {
                throw new IOException("Hostname is required" +
                                " to use Kerberos cipher suites");
            }
            KerberosClientKeyExchange kerberosMsg =
                new KerberosClientKeyExchange(
                    hostname, isLoopbackSE(), getAccSE(), protocolVersion,
                sslContext.getSecureRandom());
            // Record the principals involved in exchange
            session.setPeerPrincipal(kerberosMsg.getPeerPrincipal());
            session.setLocalPrincipal(kerberosMsg.getLocalPrincipal());
            m2 = kerberosMsg;
            break;
        default:
            // somethings very wrong
            throw new RuntimeException
                                ("Unsupported key exchange: " + keyExchange);
        }
        if (debug != null && Debug.isOn("handshake")) {
            m2.print(System.out);
        }
        m2.write(output);


        /*
         * THIRD, send a "change_cipher_spec" record followed by the
         * "Finished" message.  We flush the messages we've queued up, to
         * get concurrency between client and server.  The concurrency is
         * useful as we calculate the master secret, which is needed both
         * to compute the "Finished" message, and to compute the keys used
         * to protect all records following the change_cipher_spec.
         */

        output.doHashes();
        output.flush();

        /*
         * We deferred calculating the master secret and this connection's
         * keying data; we do it now.  Deferring this calculation is good
         * from a performance point of view, since it lets us do it during
         * some time that network delays and the server's own calculations
         * would otherwise cause to be "dead" in the critical path.
         */
        SecretKey preMasterSecret;
        switch (keyExchange) {
        case K_RSA:
        case K_RSA_EXPORT:
            preMasterSecret = ((RSAClientKeyExchange)m2).preMaster;
            break;
        case K_KRB5:
        case K_KRB5_EXPORT:
            byte[] secretBytes =
                ((KerberosClientKeyExchange)m2).getUnencryptedPreMasterSecret();
            preMasterSecret = new SecretKeySpec(secretBytes,
                "TlsPremasterSecret");
            break;
        case K_DHE_RSA:
        case K_DHE_DSS:
        case K_DH_ANON:
            preMasterSecret = dh.getAgreedSecret(serverDH, true);
            break;
        case K_ECDHE_RSA:
        case K_ECDHE_ECDSA:
        case K_ECDH_ANON:
            preMasterSecret = ecdh.getAgreedSecret(ephemeralServerKey);
            break;
        case K_ECDH_RSA:
        case K_ECDH_ECDSA:
            preMasterSecret = ecdh.getAgreedSecret(serverKey);
            break;
        default:
            throw new IOException("Internal error: unknown key exchange "
                + keyExchange);
        }

        calculateKeys(preMasterSecret, null);

        /*
         * FOURTH, if we sent a Certificate, we need to send a signed
         * CertificateVerify (unless the key in the client's certificate
         * was a Diffie-Hellman key).).
         *
         * This uses a hash of the previous handshake messages ... either
         * a nonfinal one (if the particular implementation supports it)
         * or else using the third element in the arrays of hashes being
         * computed.
         */
        if (signingKey != null) {
            CertificateVerify m3;
            try {
                SignatureAndHashAlgorithm preferableSignatureAlgorithm = null;
                if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
                    preferableSignatureAlgorithm =
                        SignatureAndHashAlgorithm.getPreferableAlgorithm(
                            peerSupportedSignAlgs, signingKey.getAlgorithm(),
                            signingKey);

                    if (preferableSignatureAlgorithm == null) {
                        throw new SSLHandshakeException(
                            "No supported signature algorithm");
                    }

                    String hashAlg =
                        SignatureAndHashAlgorithm.getHashAlgorithmName(
                                preferableSignatureAlgorithm);
                    if (hashAlg == null || hashAlg.length() == 0) {
                        throw new SSLHandshakeException(
                                "No supported hash algorithm");
                    }

                    handshakeHash.setCertificateVerifyAlg(hashAlg);
                }

                m3 = new CertificateVerify(protocolVersion, handshakeHash,
                    signingKey, session.getMasterSecret(),
                    sslContext.getSecureRandom(),
                    preferableSignatureAlgorithm);
            } catch (GeneralSecurityException e) {
                fatalSE(Alerts.alert_handshake_failure,
                    "Error signing certificate verify", e);
                // NOTREACHED, make compiler happy
                m3 = null;
            }
            if (debug != null && Debug.isOn("handshake")) {
                m3.print(System.out);
            }
            m3.write(output);
            output.doHashes();
        } else {
            if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
                handshakeHash.setCertificateVerifyAlg(null);
            }
        }

        /*
         * OK, that's that!
         */
        sendChangeCipherAndFinish(false);
    }
922681
function Client(key, password, endpoint) {
  if (!(this instanceof Client)) {
    return new Client(key, password, endpoint);
  }

  endpoint = typeof endpoint !== 'undefined' ? endpoint : Client.MODE_SANDBOX;

  var _key = key,
    _password = password,
    _endpoint = endpoint,
    _errors = [],
    _isValid = false;

  var emptyErrors = function () {
    _errors = [];
  };

  var addError = function (errorCode) {
    if (_errors.indexOf(errorCode) < 0) {
      _errors.push(errorCode);
    }
    _isValid = false;
  };

  var validate = function () {
    _isValid = true;
    if (!_key || !_password) {
      addError(ClientError.INVALID_CREDENTIAL);
    } else if (!_endpoint) {
      addError(ClientError.INVALID_ENDPOINT);
    }
    if (_errors.length > 0) {
      _isValid = false;
    }
  };

  Object.defineProperties(this, {

    /**
     * @member {String} module:Rapid/Client~Client#key
     */
    key: {
      get: function () {
        return _key;
      },
      set: function (key) {
        emptyErrors();
        _key        = key;
        Service.key = _key;
        validate();
      }
    },

    /**
     * @member {String} module:Rapid/Client~Client#password
     */
    password: {
      get: function () {
        return _password;
      },
      set: function (password) {
        emptyErrors();
        _password        = password;
        Service.password = _password;
        validate();
      }
    },

    /**
     * @member {String} module:Rapid/Client~Client#endpoint
     */
    endpoint: {
      get: function () {
        return _endpoint;
      },
      set: function (endpoint) {
        emptyErrors();
        if (endpoint) {
          switch (endpoint.toLowerCase()) {
            case Client.MODE_SANDBOX:
              _endpoint = Client.ENDPOINT_SANDBOX;
              break;
            case Client.MODE_PRODUCTION:
              _endpoint = Client.ENDPOINT_PRODUCTION;
              break;
            default:
              _endpoint = endpoint;
          }
        } else {
          _endpoint = endpoint;
        }
        Service.baseUrl = _endpoint;
        validate();
      }
    },

    /**
     * @member {Boolean} module:Rapid/Client~Client#isValid
     */
    isValid: {
      get: function () {
        return _isValid;
      }
    },

    /**
     * @member {Array} module:Rapid/Client~Client#errors
     */
    errors: {
      get: function () {
        return _errors;
      }
    }
  });

  this.setCredential(key, password);
  this.endpoint = endpoint;
}
604901
def _ignore_keys(endpoint_props):
    '''
    
    '''
    return dict(
        (prop_name, prop_val)
        for prop_name, prop_val in six.iteritems(endpoint_props)
        if prop_name not in _DO_NOT_COMPARE_FIELDS
    )
835599
function temporaryCredentials (done) {
  var strategy = this
  var provider = strategy.provider
  var endpoint = strategy.endpoints.credentials
  var client = strategy.client
  var method = endpoint.method && endpoint.method.toLowerCase()
  var url = endpoint.url
  var header = endpoint.header || 'Authorization'
  var scheme = endpoint.scheme || 'OAuth'
  var accept = endpoint.accept || 'application/x-www-form-urlencoded'
  var key = client.oauth_consumer_key
  var secret = client.oauth_consumer_secret
  var signer = provider.oauth_signature_method || 'PLAINTEXT'
  var realm = provider.realm
  var callback = provider.oauth_callback
  var params = {}

  // Initialize request
  var req = request[method || 'post'](url)

  // Build request parameters
  params.oauth_consumer_key = key
  params.oauth_signature_method = signer
  params.oauth_timestamp = timestamp()
  params.oauth_nonce = nonce(32)
  params.oauth_callback = callback
  params.oauth_version = '1.0'

  // Generate signature (is next line needed for PLAINTEXT?)
  var input = signatureBaseString(method, url, normalizeParameters(params))
  params.oauth_signature = sign(signer, input, secret)

  if (realm) { params.realm = realm }

  // Set Authorization header
  req.set(header, scheme + ' ' + authorizationHeaderParams(params))

  // Set other headers
  req.set('Accept', accept)
  req.set('User-Agent', agent)

  // Execute request
  return req.end(function (err, res) {
    if (err) { return done(err) }
    var response = qs.parse(res.text)

    if (res.statusCode !== 200) {
      return done(new Error(res.text))
    }

    done(null, response)
  })
}
1360868
def token_protected_endpoint(function):
  
  @wraps(function)
  def decorated(*args, **kwargs):
    auth_token = request.form.get('auth_token')
    if not auth_token:
      return json.dumps({
        'status': 'fail',
        'reason': 'You must provide an auth_token',
      })

    data = dict(request.form)
    del data['auth_token']
    correct_token = create_token(current_app.config['SECRET_KEY'], data)

    if _compare_digest(auth_token, correct_token):
      return function(*args, **kwargs)

    else:
      return json.dumps({
        'status': 'fail',
        'reason': 'Incorrect auth_token',
      })

  return decorated