Performs SASL authentication by sending a token, and then proceeding with the SASL
challenge-response tokens until we either successfully authenticate or throw an exception
due to mismatch.
516043
@Override
  public void doBootstrap(TransportClient client, Channel channel) {
    SparkSaslClient saslClient = new SparkSaslClient(appId, secretKeyHolder, conf.saslEncryption());
    try {
      byte[] payload = saslClient.firstToken();

      while (!saslClient.isComplete()) {
        SaslMessage msg = new SaslMessage(appId, payload);
        ByteBuf buf = Unpooled.buffer(msg.encodedLength() + (int) msg.body().size());
        msg.encode(buf);
        buf.writeBytes(msg.body().nioByteBuffer());

        ByteBuffer response = client.sendRpcSync(buf.nioBuffer(), conf.authRTTimeoutMs());
        payload = saslClient.response(JavaUtils.bufferToArray(response));
      }

      client.setClientId(appId);

      if (conf.saslEncryption()) {
        if (!SparkSaslServer.QOP_AUTH_CONF.equals(saslClient.getNegotiatedProperty(Sasl.QOP))) {
          throw new RuntimeException(
            new SaslException("Encryption requests by negotiated non-encrypted connection."));
        }

        SaslEncryption.addToChannel(channel, saslClient, conf.maxSaslEncryptedBlockSize());
        saslClient = null;
        logger.debug("Channel {} configured for encryption.", client);
      }
    } catch (IOException ioe) {
      throw new RuntimeException(ioe);
    } finally {
      if (saslClient != null) {
        try {
          // Once authentication is complete, the server will trust all remaining communication.
          saslClient.dispose();
        } catch (RuntimeException e) {
          logger.error("Error while disposing SASL client", e);
        }
      }
    }
  }
612445
@Override
    public boolean authenticate() {
        UndertowLogger.SECURITY_LOGGER.debugf("Attempting to authenticate %s, authentication required: %s", exchange.getRequestPath(), isAuthenticationRequired());
        if(authenticationState == AuthenticationState.ATTEMPTED || (authenticationState == AuthenticationState.CHALLENGE_SENT && !exchange.isResponseStarted())) {
            //we are re-attempted, so we just reset the state
            //see UNDERTOW-263
            authenticationState = AuthenticationState.NOT_ATTEMPTED;
        }
        return !authTransition();
    }
1316047
def send_challenge_response(self, response_plain):
        """"""

        # Get a basic stanza body
        body = self.get_body()

        # Create a response tag and add the response content on it
        #   using base64 encoding
        response_node = ET.SubElement(body, 'response')
        response_node.set('xmlns', XMPP_SASL_NS)
        response_node.text = base64.b64encode(response_plain)

        # Send the challenge response to server
        resp_root = ET.fromstring(self.send_request(body))
        return resp_root
1005816
@Override
  public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
    for (Callback callback : callbacks) {
      if (callback instanceof NameCallback) {
        ((NameCallback) callback).setName(username);
      } else if (callback instanceof PasswordCallback) {
        ((PasswordCallback) callback).setPassword(password.toCharArray());
      } else {
        throw new AuthenticationException("SASLClient requested unsupported callback: " + callback);
      }
    }
  }
92515
public void start()
        throws Exception
    {
        if (getHttpContext().getAuthenticator()==null)
        {
            // Find out the Authenticator.
            if (SecurityConstraint.__BASIC_AUTH.equalsIgnoreCase(_authMethod))
                getHttpContext().setAuthenticator(new BasicAuthenticator());
            else if (SecurityConstraint.__CERT_AUTH.equalsIgnoreCase(_authMethod))
                getHttpContext().setAuthenticator(new ClientCertAuthenticator());
            else
                log.warn("Unknown Authentication method:"+_authMethod);
        }
        
        super.start();
    }
533320
public void authenticate() {
        URL url;
        try {
            url = new URL(this.getTokenURL());
        } catch (MalformedURLException e) {
            assert false : "An invalid token URL indicates a bug in the SDK.";
            throw new RuntimeException("An invalid token URL indicates a bug in the SDK.", e);
        }

        String jwtAssertion = this.constructJWTAssertion();

        String urlParameters = String.format(JWT_GRANT_TYPE, this.getClientID(), this.getClientSecret(), jwtAssertion);

        BoxAPIRequest request = new BoxAPIRequest(this, url, "POST");
        request.shouldAuthenticate(false);
        request.setBody(urlParameters);

        String json;
        try {
            BoxJSONResponse response = (BoxJSONResponse) request.send();
            json = response.getJSON();
        } catch (BoxAPIException ex) {
            // Use the Date advertised by the Box server as the current time to synchronize clocks
            List<String> responseDates = ex.getHeaders().get("Date");
            NumericDate currentTime;
            if (responseDates != null) {
                String responseDate = responseDates.get(0);
                SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss zzz");
                try {
                    Date date = dateFormat.parse(responseDate);
                    currentTime = NumericDate.fromMilliseconds(date.getTime());
                } catch (ParseException e) {
                    currentTime = NumericDate.now();
                }
            } else {
                currentTime = NumericDate.now();
            }

            // Reconstruct the JWT assertion, which regenerates the jti claim, with the new "current" time
            jwtAssertion = this.constructJWTAssertion(currentTime);
            urlParameters = String.format(JWT_GRANT_TYPE, this.getClientID(), this.getClientSecret(), jwtAssertion);

            // Re-send the updated request
            request = new BoxAPIRequest(this, url, "POST");
            request.shouldAuthenticate(false);
            request.setBody(urlParameters);

            BoxJSONResponse response = (BoxJSONResponse) request.send();
            json = response.getJSON();
        }

        JsonObject jsonObject = JsonObject.readFrom(json);
        this.setAccessToken(jsonObject.get("access_token").asString());
        this.setLastRefresh(System.currentTimeMillis());
        this.setExpires(jsonObject.get("expires_in").asLong() * 1000);

        //if token cache is specified, save to cache
        if (this.accessTokenCache != null) {
            String key = this.getAccessTokenCacheKey();
            JsonObject accessTokenCacheInfo = new JsonObject()
                    .add("accessToken", this.getAccessToken())
                    .add("lastRefresh", this.getLastRefresh())
                    .add("expires", this.getExpires());

            this.accessTokenCache.put(key, accessTokenCacheInfo.toString());
        }
    }
925866
def authenticate_xmpp(self):
        """"""

        self.request_sid()

        self.log.debug('Prepare the XMPP authentication')

        # Instantiate a sasl object
        sasl = SASLClient(
            host=self.to,
            service='xmpp',
            username=self.jid,
            password=self.password
        )

        # Choose an auth mechanism
        sasl.choose_mechanism(self.server_auth, allow_anonymous=False)

        # Request challenge
        challenge = self.get_challenge(sasl.mechanism)

        # Process challenge and generate response
        response = sasl.process(base64.b64decode(challenge))

        # Send response
        resp_root = self.send_challenge_response(response)

        success = self.check_authenticate_success(resp_root)
        if success is None and\
                resp_root.find('{{{0}}}challenge'.format(XMPP_SASL_NS)) is not None:
            resp_root = self.send_challenge_response('')
            return self.check_authenticate_success(resp_root)
        return success
75978
protected void initiateAuthenticationRequest(final Pair<? extends SignableSAMLObject, MessageContext> pair,
                                                 final HttpServletResponse response,
                                                 final HttpServletRequest request) throws Exception {

        verifySamlAuthenticationRequest(pair, request);
        issueAuthenticationRequestRedirect(pair, request, response);
    }
666665
def authenticate(self, token):
        
        if self.verify_token_callback:
            # Specified verify function overrides below
            return self.verify_token_callback(token)

        if not token:
            return False

        name = self.token_manager.verify(token)
        if not name:
            return False

        return True
575746
def authenticationrequest(self, event):
        

        if event.sock.getpeername()[0] in self.failing_clients:
            self.log('Client failed a login and has to wait', lvl=debug)
            return

        if event.auto:
            self._handle_autologin(event)
        else:
            self._handle_login(event)
19952
def validate(self):
        
        if not self.api_token or not self.api_token_secret:
            raise ImproperlyConfigured("'api_token' and 'api_token_secret' are required for authentication.")

        if self.response_type not in ["json", "pson", "xml", "debug", None]:
            raise ImproperlyConfigured("'%s' is an invalid response_type" % self.response_type)
680230
def _verify_token(self):
        
        res = self._session.get(self._token_verification_url)
        if not res.ok:
            raise exceptions.BadToken(consts.LOG_MSG_BAD_TOKEN)
        return True
1182544
public void authenticateConnection (Invoker invoker, final AuthingConnection conn,
                                        final ResultListener<AuthingConnection> onComplete)
    {
        final AuthRequest req = conn.getAuthRequest();
        final AuthResponseData rdata = createResponseData();
        final AuthResponse rsp = new AuthResponse(rdata);

        invoker.postUnit(new Invoker.Unit("authenticateConnection") {
            @Override
            public boolean invoke () {
                try {
                    processAuthentication(conn, rsp);
                    if (AuthResponseData.SUCCESS.equals(rdata.code) &&
                        conn.getAuthName() == null) { // fail early, fail (less) often
                        throw new IllegalStateException("Authenticator failed to provide authname");
                    }
                } catch (AuthException e) {
                    rdata.code = e.getMessage();
                } catch (Exception e) {
                    log.warning("Error authenticating user", "areq", req, e);
                    rdata.code = AuthCodes.SERVER_ERROR;
                }
                return true;
            }

            @Override
            public void handleResult () {
                // stuff a reference to the auth response into the connection so that we have
                // access to it later in the authentication process
                conn.setAuthResponse(rsp);

                // send the response back to the client
                conn.postMessage(rsp);

                // if the authentication request was granted, let the connection manager know that
                // we just authed
                if (AuthResponseData.SUCCESS.equals(rdata.code)) {
                    onComplete.requestCompleted(conn);
                }
            }
        });
    }
1279517
private void afterExecute(HttpMethod method) throws IOException {
        AuthState hostAuthState = method.getHostAuthState();
        if (hostAuthState.isPreemptive() || hostAuthState.isAuthAttempted()) {
            AuthScheme authScheme = hostAuthState.getAuthScheme();

            if (authScheme instanceof SpnegoAuthScheme && settings.getNetworkSpnegoAuthMutual()) {
                // Perform Mutual Authentication
                SpnegoAuthScheme spnegoAuthScheme = ((SpnegoAuthScheme) authScheme);
                Map challenges = AuthChallengeParser.parseChallenges(method.getResponseHeaders(WWW_AUTHENTICATE));
                String id = spnegoAuthScheme.getSchemeName();
                String challenge = (String) challenges.get(id.toLowerCase());
                if (challenge == null) {
                    throw new IOException(id + " authorization challenge expected, but not found");
                }
                spnegoAuthScheme.ensureMutualAuth(challenge);
            }
        }
    }
352891
def sign_response(challenge)
      client_data_json = client_data(::U2F::ClientData::AUTHENTICATION_TYP, challenge)
      JSON.dump(
        clientData: ::U2F.urlsafe_encode64(client_data_json),
        keyHandle: ::U2F.urlsafe_encode64(key_handle_raw),
        signatureData: auth_signature_data(client_data_json)
      )
    end
988809
def verify_token(self, token):
        '''
        
        '''
        try:
            result = self.resolver.get_token(token)
        except Exception as ex:
            raise EauthAuthenticationError(
                "Token validation failed with {0}.".format(repr(ex)))

        return result
213739
def _verify(self, token):
        
        # Attempt to authenticate.
        url = '{}{}/'.format(self._url, 'verify')
        resp = requests.post(
            url,
            json={'token': token},
            **self._default_request_kwargs
        )
        if resp.status_code == 200:
            return resp.json().get('data', None)
        return None