Validates the captcha response.

@param request
@param challenge
@param response
@return
348692
public boolean isValid(HttpServletRequest request, String challenge, String response) {
    String remoteAddr = request.getRemoteAddr();
    log.info("Challenge Field Name = [{}]", challenge);
    log.info("Response Field Name = [{}]", response);
    if(challenge != null && response != null && challenge.trim().length() > 0) {
      return reCaptcha.checkAnswer(remoteAddr, challenge, response).isValid();
    } else {
      return false;
    }
  }
157909
def _get_auth_challenge(self, exc):
        
        response = HttpResponse(content=exc.content, status=exc.get_code_num())
        response['WWW-Authenticate'] = 'Basic realm="%s"' % REALM
        return response
1033242
void validate(ServerResponse serverResponse) throws GeneralSecurityException {
    byte[] response = validateChallenge(authNonce, serverResponse.response);

    byte[] expected = rawResponse(challenge);
    Preconditions.checkArgument(Arrays.equals(expected, response));

    byte[] nonce = decrypt(serverResponse.nonce);
    byte[] inputIv = decrypt(serverResponse.inputIv);
    byte[] outputIv = decrypt(serverResponse.outputIv);

    SecretKeySpec sessionKey = generateKey(conf.keyFactoryAlgorithm(), conf.keyFactoryIterations(),
      nonce, conf.encryptionKeyLength());
    this.sessionCipher = new TransportCipher(cryptoConf, conf.cipherTransformation(), sessionKey,
      inputIv, outputIv);
  }
429824
protected String formatCredentials(final ChallengeResponse challenge) throws GeneralSecurityException
    {
        // Data buffer
        final StringBuffer sb = new StringBuffer();
        
        // Indexes buffer
        final StringBuffer isb = new StringBuffer();
        final String timeIssued = Long.toString(System.currentTimeMillis());
        int i = timeIssued.length();
        sb.append(timeIssued);
        
        isb.append(i);
        
        final String identifier = challenge.getIdentifier();
        sb.append('/');
        sb.append(identifier);
        
        i += identifier.length() + 1;
        isb.append(',').append(i);
        
        sb.append('/');
        sb.append(challenge.getSecret());
        
        // Store indexes at the end of the string
        sb.append('/');
        sb.append(isb);
        
        return Base64.encode(
                CryptoUtils.encrypt(this.getEncryptAlgorithm(), this.getEncryptSecretKey(), sb.toString()), false);
    }
970340
def verify_challenge(uri):
    
    while True:
        try:
            resp = urlopen(uri)
            challenge_status = json.loads(resp.read().decode('utf8'))
        except IOError as e:
            raise ValueError("Error checking challenge: {0} {1}".format(
                e.code, json.loads(e.read().decode('utf8'))))
        if challenge_status['status'] == "pending":
            time.sleep(2)
        elif challenge_status['status'] == "valid":
            LOGGER.info("Domain verified!")
            break
        else:
            raise ValueError("Domain challenge did not pass: {0}".format(
                challenge_status))
556008
public static boolean validate(Controller controller, String userInputString) {
		String captchaKey = controller.getCookie(captchaName);
		if (validate(captchaKey, userInputString)) {
			controller.removeCookie(captchaName);
			return true;
		}
		return false;
	}
478540
private boolean isValid(String request) {

        String tmp = decodePercent(request);
        if(tmp.indexOf('<') != -1 ||
           tmp.indexOf('>') != -1 ) {
            return false;
        }

        return true;
    }
512466
def _assemble_and_send_validation_request(self):
        

        # Fire off the query.
        return self.client.service.validateShipment(
                WebAuthenticationDetail=self.WebAuthenticationDetail,
                ClientDetail=self.ClientDetail,
                TransactionDetail=self.TransactionDetail,
                Version=self.VersionId,
                RequestedShipment=self.RequestedShipment)
844376
def validate_token_request(self, request):
        
        # REQUIRED. Value MUST be set to "authorization_code".
        if request.grant_type not in ('authorization_code', 'openid'):
            raise errors.UnsupportedGrantTypeError(request=request)

        for validator in self.custom_validators.pre_token:
            validator(request)

        if request.code is None:
            raise errors.InvalidRequestError(
                description='Missing code parameter.', request=request)

        for param in ('client_id', 'grant_type', 'redirect_uri'):
            if param in request.duplicate_params:
                raise errors.InvalidRequestError(description='Duplicate %s parameter.' % param,
                                                 request=request)

        if self.request_validator.client_authentication_required(request):
            # If the client type is confidential or the client was issued client
            # credentials (or assigned other authentication requirements), the
            # client MUST authenticate with the authorization server as described
            # in Section 3.2.1.
            # https://tools.ietf.org/html/rfc6749#section-3.2.1
            if not self.request_validator.authenticate_client(request):
                log.debug('Client authentication failed, %r.', request)
                raise errors.InvalidClientError(request=request)
        elif not self.request_validator.authenticate_client_id(request.client_id, request):
            # REQUIRED, if the client is not authenticating with the
            # authorization server as described in Section 3.2.1.
            # https://tools.ietf.org/html/rfc6749#section-3.2.1
            log.debug('Client authentication failed, %r.', request)
            raise errors.InvalidClientError(request=request)

        if not hasattr(request.client, 'client_id'):
            raise NotImplementedError('Authenticate client must set the '
                                      'request.client.client_id attribute '
                                      'in authenticate_client.')

        request.client_id = request.client_id or request.client.client_id

        # Ensure client is authorized use of this grant type
        self.validate_grant_type(request)

        # REQUIRED. The authorization code received from the
        # authorization server.
        if not self.request_validator.validate_code(request.client_id,
                                                    request.code, request.client, request):
            log.debug('Client, %r (%r), is not allowed access to scopes %r.',
                      request.client_id, request.client, request.scopes)
            raise errors.InvalidGrantError(request=request)

        # OPTIONAL. Validate PKCE code_verifier
        challenge = self.request_validator.get_code_challenge(request.code, request)

        if challenge is not None:
            if request.code_verifier is None:
                raise errors.MissingCodeVerifierError(request=request)

            challenge_method = self.request_validator.get_code_challenge_method(request.code, request)
            if challenge_method is None:
                raise errors.InvalidGrantError(request=request, description="Challenge method not found")

            if challenge_method not in self._code_challenge_methods:
                raise errors.ServerError(
                    description="code_challenge_method {} is not supported.".format(challenge_method),
                    request=request
                )

            if not self.validate_code_challenge(challenge,
                                                challenge_method,
                                                request.code_verifier):
                log.debug('request provided a invalid code_verifier.')
                raise errors.InvalidGrantError(request=request)
        elif self.request_validator.is_pkce_required(request.client_id, request) is True:
            if request.code_verifier is None:
                raise errors.MissingCodeVerifierError(request=request)
            raise errors.InvalidGrantError(request=request, description="Challenge not found")

        for attr in ('user', 'scopes'):
            if getattr(request, attr, None) is None:
                log.debug('request.%s was not set on code validation.', attr)

        # REQUIRED, if the "redirect_uri" parameter was included in the
        # authorization request as described in Section 4.1.1, and their
        # values MUST be identical.
        if request.redirect_uri is None:
            request.using_default_redirect_uri = True
            request.redirect_uri = self.request_validator.get_default_redirect_uri(
                request.client_id, request)
            log.debug('Using default redirect_uri %s.', request.redirect_uri)
            if not request.redirect_uri:
                raise errors.MissingRedirectURIError(request=request)
        else:
            request.using_default_redirect_uri = False
            log.debug('Using provided redirect_uri %s', request.redirect_uri)

        if not self.request_validator.confirm_redirect_uri(request.client_id, request.code,
                                                           request.redirect_uri, request.client,
                                                           request):
            log.debug('Redirect_uri (%r) invalid for client %r (%r).',
                      request.redirect_uri, request.client_id, request.client)
            raise errors.MismatchingRedirectURIError(request=request)

        for validator in self.custom_validators.post_token:
            validator(request)
1338197
@Override
    protected int authenticated(final Request request, final Response response)
    {
        try
        {
            final CookieSetting credentialsCookie = this.getCredentialsCookie(request, response);
            credentialsCookie.setValue(this.formatCredentials(request.getChallengeResponse()));
            credentialsCookie.setMaxAge(this.getMaxCookieAge());
        }
        catch(final GeneralSecurityException e)
        {
            this.log.error("Could not format credentials cookie", e);
        }
        
        // log.info("calling super.authenticated");
        // return super.authenticated(request, response);
        
        // Modified copy of Authenticator.authenticated
        if(this.log.isDebugEnabled())
        {
            this.log.debug("The authentication succeeded for the identifer \"{}\" using the {} scheme.", request
                    .getChallengeResponse().getIdentifier(), request.getChallengeResponse().getScheme());
        }
        
        // Update the client info accordingly
        if(request.getClientInfo() != null)
        {
            request.getClientInfo().setAuthenticated(true);
        }
        
        // Clear previous challenge requests
        response.getChallengeRequests().clear();
        
        // Add the roles for the authenticated subject
        if(this.getEnroler() != null)
        {
            this.getEnroler().enrole(request.getClientInfo());
        }
        
        // Return STOP here works for login but not for subsequent requests that expect a response
        // return STOP;
        return Filter.CONTINUE;
    }
1016570
protected final boolean validateCaptcha(String text) {
        if (captchaSupport != null) {
            String id = Stapler.getCurrentRequest().getSession().getId();
            return captchaSupport.validateCaptcha(id, text);
        }

        // If no Captcha Support then bogus validation always returns true
        return true;
    }
67669
public function isValid($secret, Request $request)
    {
        $captcha = $request->get('g-recaptcha-response');
        if(null === $captcha || true === empty($captcha)){
            return false;
        }

        $guzzle = $this->getClient();

        $result = $guzzle->request(Request::METHOD_POST, self::URI_VERIFY_V2, [
            'form_params' => [
                'secret'   => $secret,
                'response' => $captcha,
                'remoteip' => $request->getClientIp(),
            ]
        ]);

        $bodyContents = $result->getBody()->getContents();
        if (true === empty($bodyContents)) {
            return false;
        }

        $jsonContents = json_decode($bodyContents, true);
        if (false === isset($jsonContents['success']) || true !== $jsonContents['success']) {
            return false;
        }

        return true;
    }
274867
protected final void validateSamlProtocolResponse(final Response response, final SAML2MessageContext context,
                                                      final SignatureTrustEngine engine) {

        validateSuccess(response.getStatus());

        validateSignatureIfItExists(response.getSignature(), context, engine);

        validateIssueInstant(response.getIssueInstant());

        AuthnRequest request = null;
        final SAMLMessageStore messageStorage = context.getSAMLMessageStore();
        if (messageStorage != null && response.getInResponseTo() != null) {
            final Optional<XMLObject> xmlObject = messageStorage.get(response.getInResponseTo());
            if (!xmlObject.isPresent()) {
                throw new SAMLInResponseToMismatchException("InResponseToField of the Response doesn't correspond to sent message "
                    + response.getInResponseTo());
            } else if (xmlObject.get() instanceof AuthnRequest) {
                request = (AuthnRequest) xmlObject.get();
            } else {
                throw new SAMLInResponseToMismatchException("Sent request was of different type than the expected AuthnRequest "
                    + response.getInResponseTo());
            }
        }

        verifyEndpoint(context.getSAMLEndpointContext().getEndpoint(), response.getDestination());
        if (request != null) {
            verifyRequest(request, context);
        }

        validateIssuerIfItExists(response.getIssuer(), context);
    }
1058718
def captcha_valid?(code)
      return false if session[:captcha].blank? or code.blank?
      session[:captcha].to_s.upcase == code.to_s.upcase
    end
471479
public GetVerifiedDomainResponse getVerifiedDomain(GetVerifiedDomainRequest request) {
        checkNotNull(request, "object request should not be null.");
        assertStringNotNullOrEmpty(request.getDomainName(), "object domainName should not be null or empty");

        InternalRequest internalRequest =
                this.createRequest("verifiedDomain", request, HttpMethodName.GET, request.getDomainName());
        return this.invokeHttpClient(internalRequest, GetVerifiedDomainResponse.class);
    }
1164023
public final void doCaptcha(StaplerRequest req, StaplerResponse rsp) throws IOException {
        if (captchaSupport != null) {
            String id = req.getSession().getId();
            rsp.setContentType("image/png");
            // source: https://stackoverflow.com/a/3414217
            rsp.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            rsp.setHeader("Pragma", "no-cache");
            rsp.setHeader("Expires", "0");
            captchaSupport.generateImage(id, rsp.getOutputStream());
        }
    }
549651
private boolean validateAssertion(final HttpServletRequest request, final String serviceTicketId, final Assertion assertion, final Service service) {
        for (val spec : serviceValidateConfigurationContext.getValidationSpecifications()) {
            spec.reset();
            val binder = new ServletRequestDataBinder(spec, "validationSpecification");
            initBinder(request, binder);
            binder.bind(request);
            if (!spec.isSatisfiedBy(assertion, request)) {
                LOGGER.warn("Service ticket [{}] does not satisfy validation specification.", serviceTicketId);
                return false;
            }
        }
        enforceTicketValidationAuthorizationFor(request, service, assertion);
        return true;
    }