Retrieve a Proxy Ticket from the CAS server.

@param string $target_service Url string of service to proxy
@param string &$err_code      error code
@param string &$err_msg       error message

@return string Proxy Ticket
13550
public static function retrievePT($target_service, & $err_code, & $err_msg)
    {
        phpCAS::_validateProxyExists();

        try {
            return (self::$_PHPCAS_CLIENT->retrievePT($target_service, $err_code, $err_msg));
        } catch (Exception $e) {
            phpCAS :: error(get_class($e) . ': ' . $e->getMessage());
        }
    }
285320
def _extract_tls_session_ticket(ssl_session: nassl._nassl.SSL_SESSION) -> str:
        
        session_string = ((ssl_session.as_text()).split('TLS session ticket:'))[1]
        session_tls_ticket = (session_string.split('Compression:'))[0]
        return session_tls_ticket
276430
def get_remote_client(self, target_name, user=None, password=None):
        
        if user:
            base = self.get_user_client(user, password, populate=False)
        else:
            base = weakproxy(self)
        return RemoteXCLIClient(base, target_name, populate=True)
1292905
protected <T extends Ticket> T produceTicket(final ProxyGrantingTicket proxyGrantingTicket,
                                                 final Service service, final String ticketId,
                                                 final Class<T> clazz) {
        val expirationPolicyToUse = determineExpirationPolicyForService(service);
        val result = proxyGrantingTicket.grantProxyTicket(
            ticketId,
            service,
            expirationPolicyToUse,
            this.onlyTrackMostRecentSession);

        if (!clazz.isAssignableFrom(result.getClass())) {
            throw new ClassCastException("Result [" + result
                + " is of type " + result.getClass()
                + " when we were expecting " + clazz);
        }
        return (T) result;
    }
191025
def perform_proxy_validate(self, proxied_service_ticket, headers=None):
        '''
        
        '''
        url = self._get_proxy_validate_url(ticket=proxied_service_ticket)
        logging.debug('[CAS] ProxyValidate URL: {}'.format(url))
        return self._perform_cas_call(
            url,
            ticket=proxied_service_ticket,
            headers=headers,
            )
294951
def _servicegroup_get_server(sg_name, s_name, s_port=None, **connection_args):
    '''
    
    '''
    ret = None
    servers = _servicegroup_get_servers(sg_name, **connection_args)
    if servers is None:
        return None
    for server in servers:
        if server.get_servername() == s_name:
            if s_port is not None and s_port != server.get_port():
                ret = None
            ret = server
    return ret
328291
public Object getService(TargetMetaDef targetMetaDef) {

    Debug.logVerbose("[JdonFramework] --> enter getService from dynamicProxy", module);

    Object dynamicProxy = _proxyCache.get(targetMetaDef);
    if (dynamicProxy == null) {
      dynamicProxy = getServiceFromProxy(targetMetaDef);
      _proxyCache.put(targetMetaDef, dynamicProxy);
    }
    return dynamicProxy;

  }
727340
def get(self, request, provider=None):
        
        # if settings.CAS_FEDERATE is not True redirect to the login page
        if not settings.CAS_FEDERATE:
            logger.warning("CAS_FEDERATE is False, set it to True to use federation")
            return redirect("cas_server:login")
        renew = bool(request.GET.get('renew') and request.GET['renew'] != "False")
        # Is the user is already authenticated, no need to request authentication to the user
        # identity provider.
        if self.request.session.get("authenticated") and not renew:
            logger.warning("User already authenticated, dropping federated authentication request")
            return redirect("cas_server:login")
        try:
            # get the identity provider from its suffix
            provider = FederatedIendityProvider.objects.get(suffix=provider)
            # get a CAS client for the user identity provider
            auth = self.get_cas_client(request, provider, renew)
            # if no ticket submited, redirect to the identity provider CAS login page
            if 'ticket' not in request.GET:
                logger.info("Trying to authenticate %s again" % auth.provider.server_url)
                return HttpResponseRedirect(auth.get_login_url())
            else:
                ticket = request.GET['ticket']
                try:
                    # if the ticket validation succeed
                    if auth.verify_ticket(ticket):
                        logger.info(
                            "Got a valid ticket for %s from %s" % (
                                auth.username,
                                auth.provider.server_url
                            )
                        )
                        params = utils.copy_params(request.GET, ignore={"ticket", "remember"})
                        request.session["federate_username"] = auth.federated_username
                        request.session["federate_ticket"] = ticket
                        auth.register_slo(
                            auth.federated_username,
                            request.session.session_key,
                            ticket
                        )
                        # redirect to the the login page for the user to become authenticated
                        # thanks to the `federate_username` and `federate_ticket` session parameters
                        url = utils.reverse_params("cas_server:login", params)
                        response = HttpResponseRedirect(url)
                        # If the user has checked "remember my identity provider" store it in a
                        # cookie
                        if request.GET.get("remember"):
                            max_age = settings.CAS_FEDERATE_REMEMBER_TIMEOUT
                            utils.set_cookie(
                                response,
                                "remember_provider",
                                provider.suffix,
                                max_age
                            )
                        return response
                    # else redirect to the identity provider CAS login page
                    else:
                        logger.info(
                            (
                                "Got an invalid ticket %s from %s for service %s. "
                                "Retrying authentication"
                            ) % (
                                ticket,
                                auth.provider.server_url,
                                self.service_url
                            )
                        )
                        return HttpResponseRedirect(auth.get_login_url())
                # both xml.etree.ElementTree and lxml.etree exceptions inherit from SyntaxError
                except SyntaxError as error:
                    messages.add_message(
                        request,
                        messages.ERROR,
                        _(
                            u"Invalid response from your identity provider CAS upon "
                            u"ticket %(ticket)s validation: %(error)r"
                        ) % {'ticket': ticket, 'error': error}
                    )
                    response = redirect("cas_server:login")
                    response.delete_cookie("remember_provider")
                    return response
        except FederatedIendityProvider.DoesNotExist:
            logger.warning("Identity provider suffix %s not found" % provider)
            # if the identity provider is not found, redirect to the login page
            return redirect("cas_server:login")
1067148
function cancelTarget($targetTicket) {
		$cancelTargetRequest = new cancelTarget ();
		$cancelTargetRequest->targetId = $targetTicket;
		return $this->targetService->cancelTarget ( $cancelTargetRequest );
	}
422150
protected String produceTicketIdentifier(final Service service, final TicketGrantingTicket ticketGrantingTicket,
                                             final boolean credentialProvided) {
        val uniqueTicketIdGenKey = service.getClass().getName();
        var serviceTicketUniqueTicketIdGenerator = (UniqueTicketIdGenerator) null;
        if (this.uniqueTicketIdGeneratorsForService != null && !this.uniqueTicketIdGeneratorsForService.isEmpty()) {
            LOGGER.debug("Looking up service ticket id generator for [{}]", uniqueTicketIdGenKey);
            serviceTicketUniqueTicketIdGenerator = this.uniqueTicketIdGeneratorsForService.get(uniqueTicketIdGenKey);
        }
        if (serviceTicketUniqueTicketIdGenerator == null) {
            serviceTicketUniqueTicketIdGenerator = this.defaultServiceTicketIdGenerator;
            LOGGER.debug("Service ticket id generator not found for [{}]. Using the default generator.", uniqueTicketIdGenKey);
        }

        return serviceTicketUniqueTicketIdGenerator.getNewTicketId(ServiceTicket.PREFIX);
    }
679095
function validateTicket(req, options, callback) {
  var query = {
    service: utils.getPath('service', options),
    ticket: req.query.ticket
  };
  var logger = utils.getLogger(req, options);

  if (options.paths.proxyCallback) query.pgtUrl = utils.getPath('pgtUrl', options);

  var casServerValidPath = utils.getPath('serviceValidate', options) + '?' + queryString.stringify(query);

  logger.info('Sending request to: "' + casServerValidPath + '" to validate ticket.');
  var startTime = Date.now(); 
  utils.getRequest(casServerValidPath, function(err, response) {
    /* istanbul ignore if */
    logger.access('|GET|' + casServerValidPath + '|' + (err ? 500 : response.status) + "|" + (Date.now() - startTime));
    if (err) {
      logger.error('Error when sending request to CAS server, error: ', err.toString());
      logger.error(err);
      return callback(err);
    }

    callback(null, response);
  });
}
1081009
def get(self, request):
        
        next_page = request.GET.get('next')
        required = request.GET.get('required', False)

        service_url = get_service_url(request, next_page)
        client = get_cas_client(service_url=service_url, request=request)

        if not next_page and settings.CAS_STORE_NEXT and 'CASNEXT' in request.session:
            next_page = request.session['CASNEXT']
            del request.session['CASNEXT']

        if not next_page:
            next_page = get_redirect_url(request)

        if request.user.is_authenticated:
            if settings.CAS_LOGGED_MSG is not None:
                message = settings.CAS_LOGGED_MSG % request.user.get_username()
                messages.success(request, message)
            return self.successful_login(request=request, next_page=next_page)

        ticket = request.GET.get('ticket')
        if ticket:
            user = authenticate(ticket=ticket,
                                service=service_url,
                                request=request)
            pgtiou = request.session.get("pgtiou")
            if user is not None:
                auth_login(request, user)
                if not request.session.exists(request.session.session_key):
                    request.session.create()
                SessionTicket.objects.create(
                    session_key=request.session.session_key,
                    ticket=ticket
                )

                if pgtiou and settings.CAS_PROXY_CALLBACK:
                    # Delete old PGT
                    ProxyGrantingTicket.objects.filter(
                        user=user,
                        session_key=request.session.session_key
                    ).delete()
                    # Set new PGT ticket
                    try:
                        pgt = ProxyGrantingTicket.objects.get(pgtiou=pgtiou)
                        pgt.user = user
                        pgt.session_key = request.session.session_key
                        pgt.save()
                    except ProxyGrantingTicket.DoesNotExist:
                        pass

                if settings.CAS_LOGIN_MSG is not None:
                    name = user.get_username()
                    message = settings.CAS_LOGIN_MSG % name
                    messages.success(request, message)
                return self.successful_login(request=request, next_page=next_page)
            elif settings.CAS_RETRY_LOGIN or required:
                return HttpResponseRedirect(client.get_login_url())
            else:
                raise PermissionDenied(_('Login failed.'))
        else:
            if settings.CAS_STORE_NEXT:
                request.session['CASNEXT'] = next_page
            return HttpResponseRedirect(client.get_login_url())
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
      });
    });

}
718967
def getServiceMessages(self, remote):
        """"""
        try:
            return self.proxies["%s-%s" % (self._interface_id, remote)].getServiceMessages()
        except Exception as err:
            LOG.debug("ServerThread.getServiceMessages: Exception: %s" % str(err))
1246772
def _internal_verify_cas(ticket, service, suffix):
    

    params = {'ticket': ticket, 'service': service}
    if settings.CAS_PROXY_CALLBACK:
        params['pgtUrl'] = settings.CAS_PROXY_CALLBACK

    url = (urljoin(settings.CAS_SERVER_URL, suffix) + '?' +
           urlencode(params))

    page = urlopen(url)

    username = None

    try:
        response = page.read()
        tree = ElementTree.fromstring(response)
        document = minidom.parseString(response)

        if tree[0].tag.endswith('authenticationSuccess'):
            if settings.CAS_RESPONSE_CALLBACKS:
                cas_response_callbacks(tree)

            username = tree[0][0].text

            pgt_el = document.getElementsByTagName('cas:proxyGrantingTicket')

            if pgt_el:
                pgt = pgt_el[0].firstChild.nodeValue
                try:
                    pgtIou = _get_pgtiou(pgt)
                    tgt = Tgt.objects.get(username=username)
                    tgt.tgt = pgtIou.tgt
                    tgt.save()
                    pgtIou.delete()
                except Tgt.DoesNotExist:
                    Tgt.objects.create(username=username, tgt=pgtIou.tgt)
                    logger.info('Creating TGT ticket for {user}'.format(
                        user=username
                    ))
                    pgtIou.delete()
                except Exception as e:
                    logger.warning('Failed to do proxy authentication. {message}'.format(
                        message=e
                    ))

        else:
            failure = document.getElementsByTagName('cas:authenticationFailure')
            if failure:
                logger.warn('Authentication failed from CAS server: %s',
                            failure[0].firstChild.nodeValue)

    except Exception as e:
        logger.error('Failed to verify CAS authentication: {message}'.format(
            message=e
        ))

    finally:
        page.close()

    return username
1024427
def getServiceRequest(self, request, target):
        
        try:
            return self._request_class(
                request.envelope, self.services[target], None)
        except KeyError:
            pass

        try:
            sp = target.split('.')
            name, meth = '.'.join(sp[:-1]), sp[-1]

            return self._request_class(
                request.envelope, self.services[name], meth)
        except (ValueError, KeyError):
            pass

        raise UnknownServiceError("Unknown service %s" % target)
795929
protected String produceTicketIdentifier(final Service service) {
        val uniqueTicketIdGenKey = service.getClass().getName();
        LOGGER.debug("Looking up ticket id generator for [{}]", uniqueTicketIdGenKey);
        var generator = this.uniqueTicketIdGeneratorsForService.get(uniqueTicketIdGenKey);
        if (generator == null) {
            generator = this.defaultTicketIdGenerator;
            LOGGER.debug("Ticket id generator not found for [{}]. Using the default generator...", uniqueTicketIdGenKey);
        }

        val ticketId = generator.getNewTicketId(ProxyTicket.PROXY_TICKET_PREFIX);
        if (this.cipherExecutor == null) {
            return ticketId;
        }
        LOGGER.trace("Attempting to encode proxy ticket [{}]", ticketId);
        val encodedId = this.cipherExecutor.encode(ticketId);
        LOGGER.debug("Encoded proxy ticket id [{}]", encodedId);
        return encodedId;
    }