Verifies CAS ticket and gets or creates User object
        NB: Use of PT to identify proxy
500398
def authenticate(self, request, ticket, service):
        

        User = get_user_model()
        username = _verify(ticket, service)

        if not username:
            return None

        try:
            user = User.objects.get(username__iexact=username)
        except User.DoesNotExist:
            # user will have an "unusable" password
            if settings.CAS_AUTO_CREATE_USER:
                user = User.objects.create_user(username, '')
                user.save()
            else:
                user = None
        return user
689044
def verify_ticket(self, ticket):
        """"""
        (response, charset) = self.get_verification_response(ticket)
        return self.verify_response(response, charset)
168333
def login(request, next_page=None, required=False, gateway=False):
    

    if not next_page:
        next_page = _redirect_url(request)

    try:
        # use callable for pre-django 2.0
        is_authenticated = request.user.is_authenticated()
    except TypeError:
        is_authenticated = request.user.is_authenticated

    if is_authenticated:
        return HttpResponseRedirect(next_page)

    ticket = request.GET.get('ticket')

    if gateway:
        service = _service_url(request, next_page, True)
    else:
        service = _service_url(request, next_page, False)

    if ticket:
        user = auth.authenticate(ticket=ticket, service=service)

        if user is not None:

            auth.login(request, user)

            if settings.CAS_PROXY_CALLBACK:
                proxy_callback(request)

            return HttpResponseRedirect(next_page)
        elif settings.CAS_RETRY_LOGIN or required:
            if gateway:
                return HttpResponseRedirect(_login_url(service, ticket, True))
            else:
                return HttpResponseRedirect(_login_url(service, ticket, False))
        else:
            logger.warning('User has a valid ticket but not a valid session')
            # Has ticket, not session

            if gateway:
                # Gatewayed responses should nto redirect.
                return False

            if getattr(settings, 'CAS_CUSTOM_FORBIDDEN'):
                return HttpResponseRedirect(reverse(settings.CAS_CUSTOM_FORBIDDEN) + "?" + request.META['QUERY_STRING'])
            else:
                error = "<h1>Forbidden</h1><p>Login failed.</p>"
                return HttpResponseForbidden(error)
    else:
        if gateway:
            return HttpResponseRedirect(_login_url(service, ticket, True))
        else:
            return HttpResponseRedirect(_login_url(service, ticket, False))
863014
public function verify($ticket, $randStr, $userIP)
    {
        $contents = $this->filesystem
            ->getAdapter()
            ->getHttpClient()
            ->get(self::TICKET_VERIFY, ['query' => [
                'aid'          => $this->aid,
                'AppSecretKey' => $this->appSecretKey,
                'Ticket'       => $ticket,
                'Randstr'      => $randStr,
                'UserIP'       => $userIP,
            ]])
            ->getBody()
            ->getContents();

        return \GuzzleHttp\json_decode($contents);
    }
1036395
private void verifyHostname(X509Certificate cer) {
        try {
            hostnameVerifier.verify(expectedCertCommonName, cer);
        } catch (SSLException e) {
            throw new SdkClientException("Certificate does not match expected common name: " + expectedCertCommonName, e);
        }
    }
728208
def verify(self, connection_type=None):
        
        req_body = self._cli.make_body(connectionType=connection_type)

        resp = self.action('verify', **req_body)
        resp.raise_if_err()
        return resp
1316444
private function configureCasClient()
    {
        $method = !$this->config['cas_proxy'] ? 'client' : 'proxy';
        // Last argument of method (proxy or client) is $changeSessionID. It is true by default. It means it will
        // override the framework's session_id. This allows for Single Sign Out. And it means that there is no point
        // in using the framework's session and authentication objects. If CAS destroys the session, it will destroy it
        // for everyone and you only need to deal with one session.
        phpCAS::$method(
            !$this->config['cas_saml'] ? CAS_VERSION_2_0 : SAML_VERSION_1_1,
            $this->config['cas_hostname'],
            (integer) $this->config['cas_port'],
            $this->config['cas_uri']
        );
    }
1328704
def init_post(self, request):
        
        self.request = request
        self.service = request.POST.get('service')
        self.renew = bool(request.POST.get('renew') and request.POST['renew'] != "False")
        self.gateway = request.POST.get('gateway')
        self.method = request.POST.get('method')
        self.ajax = settings.CAS_ENABLE_AJAX_AUTH and 'HTTP_X_AJAX' in request.META
        if request.POST.get('warned') and request.POST['warned'] != "False":
            self.warned = True
        self.warn = request.POST.get('warn')
        if settings.CAS_FEDERATE:
            self.username = request.POST.get('username')
            # in federated mode, the valdated indentity provider CAS ticket is used as password
            self.ticket = request.POST.get('password')
2223
def validate_callback(self, service, pgturl, pgtid, pgtiou):
        """"""
        if not proxy_allowed(service):
            raise UnauthorizedServiceProxy("%s is not authorized to use proxy authentication" % service)

        if not is_scheme_https(pgturl):
            raise InvalidProxyCallback("Proxy callback %s is not HTTPS" % pgturl)

        if not proxy_callback_allowed(service, pgturl):
            raise InvalidProxyCallback("%s is not an authorized proxy callback URL" % pgturl)

        # Verify that the SSL certificate is valid
        verify = os.environ.get('REQUESTS_CA_BUNDLE', True)
        try:
            requests.get(pgturl, verify=verify, timeout=5)
        except requests.exceptions.SSLError:
            raise InvalidProxyCallback("SSL certificate validation failed for proxy callback %s" % pgturl)
        except requests.exceptions.RequestException as e:
            raise InvalidProxyCallback(e)

        # Callback certificate appears valid, so send the ticket strings
        pgturl = add_query_params(pgturl, {'pgtId': pgtid, 'pgtIou': pgtiou})
        try:
            response = requests.get(pgturl, verify=verify, timeout=5)
        except requests.exceptions.RequestException as e:
            raise InvalidProxyCallback(e)

        try:
            response.raise_for_status()
        except requests.exceptions.HTTPError as e:
            raise InvalidProxyCallback("Proxy callback %s returned %s" % (pgturl, e))
25398
def create_ticket(subject, tags, ticket_body, requester_email=None,
                  custom_fields=[]):
    

    payload = {'ticket': {
        'subject': subject,
        'comment': {
            'body': ticket_body
        },
        'group_id': settings.ZENDESK_GROUP_ID,
        'tags': tags,
        'custom_fields': custom_fields
    }}

    if requester_email:
        payload['ticket']['requester'] = {
            'name': 'Sender: %s' % requester_email.split('@')[0],
            'email': requester_email,
        }
    else:
        payload['ticket']['requester_id'] = settings.ZENDESK_REQUESTER_ID

    requests.post(
        get_ticket_endpoint(),
        data=json.dumps(payload),
        auth=zendesk_auth(),
        headers={'content-type': 'application/json'}).raise_for_status()
1174248
def proxy_callback_allowed(service, pgturl):
    """"""
    if hasattr(settings, 'MAMA_CAS_SERVICES'):
        return _is_allowed('proxy_callback_allowed', service, pgturl)
    return _is_valid_service_url(service)
416330
def create_ticket
      post_param = { username: @username, realm: @realm, password: @password }
      @site['access/ticket'].post post_param do |response, _request, _result, &_block|
        if response.code == 200
          extract_ticket response
        else
          @connection_status = 'error'
        end
      end
    end
568059
def validate_proxy_ticket(service, ticket, pgturl=None):
    
    logger.debug("Proxy validation request received for %s" % ticket)

    pt = ProxyTicket.objects.validate_ticket(ticket, service)
    attributes = get_attributes(pt.user, pt.service)

    # Build a list of all services that proxied authentication,
    # in reverse order of which they were traversed
    proxies = [pt.service]
    prior_pt = pt.granted_by_pgt.granted_by_pt
    while prior_pt:
        proxies.append(prior_pt.service)
        prior_pt = prior_pt.granted_by_pgt.granted_by_pt

    if pgturl is not None:
        logger.debug("Proxy-granting ticket request received for %s" % pgturl)
        pgt = ProxyGrantingTicket.objects.create_ticket(service, pgturl, user=pt.user, granted_by_pt=pt)
    else:
        pgt = None
    return pt, attributes, pgt, proxies
915948
function validateService(res, url, callback) {
  if (debug) {
    console.log('Sending request to: "' + url + '" to validate ticket.');
  }

  fetch(url).then(function(res) {
      if (res.status == 200) {
        return res.text();
      } else {
        console.log('Receive response from cas when validating ticket, but request failed with status code: ' + casRes.statusCode + '!');
        res.status(401).send({
          message: 'Receive response from cas when validating ticket, but request failed with status code: ' + casRes.statusCode + '.'
        });
      }
    })
    .then(function(casBody) {
      if (casBody) {
        if (debug) {
          console.log('Receive response from CAS when validating ticket with status code 200, casBody: ', casBody);
        }

        callback(casBody);
      }
    })
    .catch(function(err) {
      console.log('Receive response from cas when validating ticket, but request failed!');
      console.error(err);
      return res.status(401).send({
        message: 'Receive response from cas when validating ticket, but request failed!',
        error: err
      });
    });

}
126401
def perform
      validate!

      party_options = options.dup

      # merge proxy
      if proxy = self.proxy
        addr, port = proxy.split(':')
        party_options[:http_proxyaddr] = addr
        party_options[:http_proxyport] = port || 80
      end

      # now merge runtime_options
      party_options = party_options.merge(sinew.runtime_options.httparty_options)

      # merge headers
      headers = sinew.runtime_options.headers
      headers = headers.merge(party_options[:headers]) if party_options[:headers]
      party_options[:headers] = headers

      party_response = HTTParty.send(method, uri, party_options)
      Response.from_network(self, party_response)
    end
1343383
@Override
    public Account verify(Credential credential) {
        assertMechanism(AuthMechanism.CLIENT_CERT, AuthMechanism.KERBEROS);

        final AuthorizingCallbackHandler ach;
        final Principal user;
        if (credential instanceof X509CertificateCredential) {
            X509CertificateCredential certCred = (X509CertificateCredential) credential;

            ach = securityRealm.getAuthorizingCallbackHandler(AuthMechanism.CLIENT_CERT);
            user = certCred.getCertificate().getSubjectDN();
        } else if (credential instanceof GSSContextCredential) {
            GSSContextCredential gssCred = (GSSContextCredential) credential;
            try {
            user = new KerberosPrincipal(gssCred.getGssContext().getSrcName().toString());
            } catch (GSSException e) {
                // By this point this should not be able to happen.
                ROOT_LOGGER.debug("Unexpected authentication failure", e);
                return null;
            }
            ach = securityRealm.getAuthorizingCallbackHandler(AuthMechanism.KERBEROS);
        } else {
            return null;
        }

        try {
            ach.handle(new Callback[] { new AuthorizeCallback(user.getName(), user.getName()) });
        } catch (IOException e) {
            ROOT_LOGGER.debug("Unexpected authentication failure", e);
            return null;
        } catch (UnsupportedCallbackException e) {
            ROOT_LOGGER.debug("Unexpected authentication failure", e);
            return null;
        }

        Collection<Principal> userCol = Collections.singleton(user);
        SubjectUserInfo supplemental;
        try {
            supplemental = ach.createSubjectUserInfo(userCol);
        } catch (IOException e) {
            return null;
        }
        addInetPrincipal(supplemental.getSubject().getPrincipals());

        return new RealmIdentityAccount(supplemental.getSubject(), user);
    }
1349703
def get_proxy_ticket(self, pgt):
        """"""
        response = urllib_request.urlopen(self.get_proxy_url(pgt))
        if response.code == 200:
            from lxml import etree
            root = etree.fromstring(response.read())
            tickets = root.xpath(
                "//cas:proxyTicket",
                namespaces={"cas": "http://www.yale.edu/tp/cas"}
            )
            if len(tickets) == 1:
                return tickets[0].text
            errors = root.xpath(
                "//cas:authenticationFailure",
                namespaces={"cas": "http://www.yale.edu/tp/cas"}
            )
            if len(errors) == 1:
                raise CASError(errors[0].attrib['code'], errors[0].text)
        raise CASError("Bad http code %s" % response.code)