Creates the plain text JWT.
3527
protected String createPlainTextJWT() {
        com.google.gson.JsonObject header = createHeader();
        com.google.gson.JsonObject payload = createPayload();

        String plainTextTokenString = computeBaseString(header, payload);
        StringBuffer sb = new StringBuffer(plainTextTokenString);
        sb.append(".").append("");
        return sb.toString();
    }
1066720
def get_JWT(url, address=None):
    
    jwt_txt = None
    jwt = None

    log.debug("Try {}".format(url))

    # special case: handle file://
    urlinfo = urllib2.urlparse.urlparse(url)
    if urlinfo.scheme == 'file':
        # points to a path on disk
        try:
            with open(urlinfo.path, 'r') as f:
                jwt_txt = f.read()

        except Exception as e:
            if BLOCKSTACK_TEST:
                log.exception(e)

            log.warning("Failed to read {}".format(url))
            return None

    else:
        # http(s) URL or similar
        try:
            resp = requests.get(url)
            assert resp.status_code == 200, 'Bad status code on {}: {}'.format(url, resp.status_code)
            jwt_txt = resp.text

        except Exception as e:
            if BLOCKSTACK_TEST:
                log.exception(e)

            log.warning("Unable to resolve {}".format(url))
            return None

    try:
        # one of two things are possible:
        # * this is a JWT string
        # * this is a serialized JSON string whose first item is a dict that has 'token' as key,
        # and that key is a JWT string.
        try:
            jwt_txt = json.loads(jwt_txt)[0]['token']
        except:
            pass

        jwt = jsontokens.decode_token(jwt_txt)
    except Exception as e:
        if BLOCKSTACK_TEST:
            log.exception(e)

        log.warning("Unable to decode token at {}".format(url))
        return None

    try:
        # must be well-formed
        assert isinstance(jwt, dict)
        assert 'payload' in jwt, jwt
        assert isinstance(jwt['payload'], dict)
        assert 'issuer' in jwt['payload'], jwt
        assert isinstance(jwt['payload']['issuer'], dict)
        assert 'publicKey' in jwt['payload']['issuer'], jwt
        assert virtualchain.ecdsalib.ecdsa_public_key(str(jwt['payload']['issuer']['publicKey']))

    except AssertionError as ae:
        if BLOCKSTACK_TEST or BLOCKSTACK_DEBUG:
            log.exception(ae)

        log.warning("JWT at {} is malformed".format(url))
        return None

    if address is not None:
        public_key = str(jwt['payload']['issuer']['publicKey'])
        addrs = [virtualchain.address_reencode(virtualchain.ecdsalib.ecdsa_public_key(keylib.key_formatting.decompress(public_key)).address()),
                 virtualchain.address_reencode(virtualchain.ecdsalib.ecdsa_public_key(keylib.key_formatting.compress(public_key)).address())]

        if virtualchain.address_reencode(address) not in addrs:
            # got a JWT, but it doesn't match the address
            log.warning("Found JWT at {}, but its public key has addresses {} and {} (expected {})".format(url, addrs[0], addrs[1], address))
            return None

        verifier = jsontokens.TokenVerifier()
        if not verifier.verify(jwt_txt, public_key):
            # got a JWT, and the address matches, but the signature does not
            log.warning("Found JWT at {}, but it was not signed by {} ({})".format(url, public_key, address))
            return None

    return jwt
181237
def _make_jwt(self):
        
        now = _helpers.utcnow()
        lifetime = datetime.timedelta(seconds=self._token_lifetime)
        expiry = now + lifetime

        payload = {
            'iss': self._issuer,
            'sub': self._subject,
            'iat': _helpers.datetime_to_secs(now),
            'exp': _helpers.datetime_to_secs(expiry),
            'aud': self._audience,
        }

        payload.update(self._additional_claims)

        jwt = encode(self._signer, payload)

        return jwt, expiry
809326
def _message_from_token(self, token: Text, payload: Any) \
            -> Optional[BaseMessage]:
        

        try:
            tk = jwt.decode(token, settings.WEBVIEW_SECRET_KEY)
        except jwt.InvalidTokenError:
            return

        try:
            user_id = tk['fb_psid']
            assert isinstance(user_id, Text)
            page_id = tk['fb_pid']
            assert isinstance(page_id, Text)
        except (KeyError, AssertionError):
            return

        if self.settings()['page_id'] == page_id:
            return self._make_fake_message(user_id, page_id, payload)
884802
public static String getJwt(JwtClaims claims) throws JoseException {
        String jwt;
        RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey(
                jwtConfig.getKey().getFilename(), (String)secretConfig.get(JWT_PRIVATE_KEY_PASSWORD), jwtConfig.getKey().getKeyName());

        // A JWT is a JWS and/or a JWE with JSON claims as the payload.
        // In this example it is a JWS nested inside a JWE
        // So we first create a JsonWebSignature object.
        JsonWebSignature jws = new JsonWebSignature();

        // The payload of the JWS is JSON content of the JWT Claims
        jws.setPayload(claims.toJson());

        // The JWT is signed using the sender's private key
        jws.setKey(privateKey);

        // Get provider from security config file, it should be two digit
        // And the provider id will set as prefix for keyid in the token header, for example: 05100
        // if there is no provider id, we use "00" for the default value
        String provider_id = "";
        if (jwtConfig.getProviderId() != null) {
            provider_id = jwtConfig.getProviderId();
            if (provider_id.length() == 1) {
                provider_id = "0" + provider_id;
            } else if (provider_id.length() > 2) {
                logger.error("provider_id defined in the security.yml file is invalid; the length should be 2");
                provider_id = provider_id.substring(0, 2);
            }
        }
        jws.setKeyIdHeaderValue(provider_id + jwtConfig.getKey().getKid());

        // Set the signature algorithm on the JWT/JWS that will integrity protect the claims
        jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);

        // Sign the JWS and produce the compact serialization, which will be the inner JWT/JWS
        // representation, which is a string consisting of three dot ('.') separated
        // base64url-encoded parts in the form Header.Payload.Signature
        jwt = jws.getCompactSerialization();
        return jwt;
    }
796312
def generate_token(self):
        """"""

        response = self._make_request()
        self.auth = response
        self.token = response['token']
192865
def plaintext(method, options = {})
      bootstrap = form_bootstrap.scoped(options.delete(:bootstrap))
      draw_form_group(bootstrap, method, options) do
        remove_css_class!(options, "form-control")
        add_css_class!(options, "form-control-plaintext")
        options[:readonly] = true
        ActionView::Helpers::FormBuilder.instance_method(:text_field).bind(self).call(method, options)
      end
    end
51391
public String generateJwt() throws NexmoUnacceptableAuthException {
        JWTAuthMethod authMethod = this.httpWrapper.getAuthCollection().getAuth(JWTAuthMethod.class);
        return authMethod.constructToken(System.currentTimeMillis() / 1000L, JWTAuthMethod.constructJTI());
    }
677754
function createHtmlText(tokens) {
  var htmlText = '';

  tokens.forEach(function(t) {
    if (t.matched) {
      htmlText += '<strong class="' + SearchPad.RESULT_HIGHLIGHT_CLASS + '">' + t.matched + '</strong>';
    } else {
      htmlText += t.normal;
    }
  });

  return htmlText !== '' ? htmlText : null;
}
742093
def header(certificate)
      x5t = thumbprint(certificate)
      logger.verbose("Creating self signed JWT header with thumbprint: #{x5t}.")
      { TYPE => TYPE_JWT,
        ALGORITHM => RS256,
        THUMBPRINT => x5t }
    end
1129084
def jwt_proccessor():
    """"""
    def jwt():
        """Context processor function to generate jwt."""
        token = current_accounts.jwt_creation_factory()
        return Markup(
            render_template(
                current_app.config['ACCOUNTS_JWT_DOM_TOKEN_TEMPLATE'],
                token=token
            )
        )

    def jwt_token():
        """Context processor function to generate jwt."""
        return current_accounts.jwt_creation_factory()

    return {
        'jwt': jwt,
        'jwt_token': jwt_token,
    }
355219
def to_plaintext(options = :DEFAULT, width = 120)
      opts = Config.process_options(options, :render)
      _render_plaintext(opts, width).force_encoding('utf-8')
    end
830106
function(jwt) {
  try {
    var segments = jwt.split('.');
    this.signature = segments.pop();
    this.signatureBase = segments.join('.');
    this.header = decodeSegment(segments.shift());
    this.payload = decodeSegment(segments.shift());
  } catch (e) {
    throw new Error("Unable to parse JWT");
  }
}
1114918
function JWT (options) {
  options = options || {};
  var optionDefaults = {
    crypto: {
      algorithm: 'HS256'
    },
    header: {
      typ: 'JWT'
    },
    claims: {},
    validations: {}
  };
  _.defaultsDeep(options, optionDefaults);

  // -- Private
  var isHmac = false;
  var isSign = false;
  var isUnsecured = false;
  var validations;

  var algPrefix;
  var algBitLength;
  var algorithm;
  var crypto;

  var privateKey;
  var publicKey;
  var secret;

  var jwtClaims;
  var jwtHeader;

  function processKey (key) {
    if (!_.isUndefined(key)) {
      if (Buffer.isBuffer(key)) {
        return key.toString();
      } else {
        return key;
      }
    } else {
      return key;
    }
  }

  // -- Protected
  this.isHmac = function () {
    return isHmac;
  };

  this.isSign = function () {
    return isSign;
  };

  this.isUnsecured = function () {
    return isUnsecured;
  };

  this.getAlgorithm = function () {
    return algorithm;
  };

  this.getCrypto = function () {
    return crypto;
  };

  this.getHeader = function () {
    return jwtHeader;
  };

  this.getClaims = function () {
    return jwtClaims;
  };

  this.getSecret = function () {
    return secret;
  };

  this.getPrivateKey = function () {
    return privateKey;
  };

  this.getPublicKey = function () {
    return publicKey;
  };

  this.getValidations = function () {
    return validations;
  };

  // Public
  this.setValidations = function (obj) {
    validations = obj || {};
    return this;
  };

  this.setPrivateKey = function (key) {
    privateKey = processKey.bind(this)(key) || undefined;
    return this;
  };

  this.setPublicKey = function (key) {
    publicKey = processKey.bind(this)(key) || undefined;
    return this;
  };

  this.setSecret = function (sec) {
    if (!_.isUndefined(sec)) {
      if (Buffer.isBuffer(sec)) {
        secret =  sec.toString();
      } else {
        secret = sec;
      }
    } else {
      secret = sec;
    }
    return this;
  };

  this.setAlgorithm = function (alg) {
    if (_.has(JWT.getSupportedAlgorithms(), alg)) {
      jwtHeader = _.merge(options.header, { alg: alg.toUpperCase() });
      if (alg === 'NONE') {
        isHmac = false;
        isSign = false;
        isUnsecured = true;
        crypto = '';
      } else {
        algorithm = alg.toUpperCase();
        algPrefix = alg.substring(0,2);
        algBitLength = alg.substring(2,5);

        // Set type key
        if (algPrefix === 'RS'
            || algPrefix === 'ES'
            || algPrefix === 'PS'
        ) {
          isHmac = false;
          isSign = true;
          isUnsecured = false;
          crypto = 'RSA-SHA' + algBitLength;
        } else {
          isHmac = true;
          isSign = false;
          isUnsecured = false;
          crypto = 'sha' + algBitLength;
        }
      }
    } else {
      throw new JWTError(JWT_UNKNOWN_ALGORITHM + ' ' +  alg);
    }
    return this;
  };

  this.setClaims = function(claims) {
    jwtClaims = claims;
    return this;
  };

  //-- Initialization
  // Set header / alg
  this.setAlgorithm(options.crypto.algorithm);

  // Set secret / keys
  if (!_.isUndefined(options.crypto.secret)) {
    this.setSecret(options.crypto.secret);
  }

  if (!_.isUndefined(options.crypto.privateKey)) {
    this.setPrivateKey(options.crypto.privateKey);
  }

  if (!_.isUndefined(options.crypto.publicKey)) {
    this.setPublicKey(options.crypto.publicKey);
  }

  // Set default claims
  this.setClaims(options.claims);

  // Set Validations
  this.setValidations(options.validations);

  // Return instance
  return this;
}
278365
def render(self, text, auth=None):
        
        # Ensure text is Unicode
        expected = str if sys.version_info[0] >= 3 else unicode  # noqa
        if not isinstance(text, expected):
            raise TypeError(
                'Expected a Unicode string, got {!r}.'.format(text))

        if self.user_content:
            url = '{0}/markdown'.format(self.api_url)
            data = {'text': text, 'mode': 'gfm'}
            if self.context:
                data['context'] = self.context
            data = json.dumps(data, ensure_ascii=False).encode('utf-8')
            headers = {'content-type': 'application/json; charset=UTF-8'}
        else:
            url = '{0}/markdown/raw'.format(self.api_url)
            data = text.encode('utf-8')
            headers = {'content-type': 'text/x-markdown; charset=UTF-8'}

        r = requests.post(url, headers=headers, data=data, auth=auth)
        r.raise_for_status()

        # FUTURE: Remove this once GitHub API properly handles Unicode markdown
        r.encoding = 'utf-8'

        return r.text if self.raw else patch(r.text)
590549
function Parse ( token ) {
  if ( typeof token != 'string' )
      throw new Error('JWT must be a string object')

  var parts = token.split('.')

  if (!parts.every(b64url.valid))
      throw new Error('JWT contains invalid URL safe Base64 chars')
  try {
    this.header = JSON.parse( b64url.decode( parts[0] ) )
  }
  catch (e) {
      return e
  }
  if (!this.header.typ)
      throw new Error('No "typ" in JWT header')

  if (this.header.typ == 'JWS') {
    try {
      this.payload = JSON.parse( b64url.decode( parts[1] ) )
    }
    catch (e) {
        return e
    }
    this._input = parts[0] +'.'+ parts[1]
    this.signature = parts[2]
    return this

  } else if (this.header.typ == 'JWE') {
    if (parts.length != 5)
      throw new Error('Invalid JWE token, does not have 5 components')
    this._input = parts[0] +'.'+ parts[1] +'.'+ parts[2] +'.'+ parts[3]
    this._cmk = parts[1]
    this._iv = parts[2]
    this._ciphertext = parts[3]
    this.signature = parts[4]
    return this

  } else
    throw new Error('Uknownn JWT header "typ":"'+this.header.typ+'"')
}
858847
async def _send_plain_text(self, request: Request, stack: Stack):
        

        await self._send_text(request, stack, None)