http://wiki.usaepay.com/developer/soap-1.4/objects/uesecuritytoken
540457
def security_token(gateway_options)
      t = Time.now
      hash = Hash.new
      hash["Seed"] = "#{t.year}#{t.month}#{t.day}#{t.hour}#{rand(1000)}"
      hash["Type"] = 'sha1'

      prehash = "#{@source_key}#{hash["Seed"]}#{@pin.to_s.strip}"
      hash["HashValue"] = Digest::SHA1.hexdigest(prehash).to_s

      token = Hash.new
      token["ClientIP"] = gateway_options[:ip]
      token["PinHash"] = hash
      token["SourceKey"] = @source_key
      token
    end
1204214
private static EsToken getEsAuthToken(ClusterName clusterName, User user) {
        return user.getEsToken(clusterName.getName());
    }
1010767
def _token_extensions(self):
        
        token_provider = self.config['sasl_oauth_token_provider']

        # Only run if the #extensions() method is implemented by the clients Token Provider class
        # Builds up a string separated by \x01 via a dict of key value pairs
        if callable(getattr(token_provider, "extensions", None)) and len(token_provider.extensions()) > 0:
            msg = "\x01".join(["{}={}".format(k, v) for k, v in token_provider.extensions().items()])
            return "\x01" + msg
        else:
            return ""
221113
function createToken(username, done) {
  return getUser(username, function(getUserErr, user) {
    if (getUserErr) {
      return done(getUserErr);
    }

    if (!user) {
      return done(new Error(`user '${username}' not found`));
    }

    const token = uuid.v4();

    return hashToken(token, function(cryptErr, hash) {
      if (cryptErr) {
        return done(cryptErr);
      }

      return getModels(function(m) {
        m.collections.token.create({
          uuid: hash,
          owner: user.id,
        }, function(createTokenErr) {
          if (createTokenErr) {
            return done(createTokenErr);
          }

          return done(null, token);
        }); // m.collections.token.create
      }); // getModels
    }); // hashToken
  }); // getUser
}
356461
public static String generateSecurityToken(int length, boolean urlSafe) {
		final byte[] bytes = new byte[length];
		SecureRandom rand;
		try {
			rand = SecureRandom.getInstance("SHA1PRNG");
		} catch (NoSuchAlgorithmException ex) {
			logger.error(null, ex);
			rand = new SecureRandom();
		}
		rand.nextBytes(bytes);
		return urlSafe ? base64encURL(bytes) : base64enc(bytes);
	}
294947
def _generateForTokenSecurity(self,
                                  username, password,
                                  tokenUrl,
                                  expiration=None,
                                  client='requestip'):
        

        query_dict = {'username': username,
                      'password': password,
                      'expiration':str(_defaultTokenExpiration),
                      'client': client,
                      'f': 'json'}
        if client == "referer":
            query_dict['referer'] = self._referer_url
        if expiration is not None:
            query_dict['expiration'] = expiration

        secHandler = None
        if self.cookiejar is not None:
            secHandler = self
            if secHandler is not None:
                secHandler._method = "HANDLER"
        token = self._post(url=tokenUrl,
                           param_dict=query_dict,
                           securityHandler=secHandler,
                           proxy_port=self._proxy_port,
                           proxy_url=self._proxy_url)
        if self.cookiejar is not None:
            if secHandler is not None:
                secHandler._method = "TOKEN"
        if 'error' in token:
            self._token = None
            self._token_created_on = None
            self._token_expires_on = None
            self._expires_in = None

            return token
        elif 'status' in token:
            self._token = None
            self._token_created_on = None
            self._token_expires_on = None
            self._expires_in = None
            #print token['message']
            return token

        else:
            self._token = token['token']
            self._token_created_on = datetime.datetime.now()
            self._token_expires_on = datetime.datetime.fromtimestamp(token['expires'] /1000) - \
                datetime.timedelta(seconds=1)
            self._expires_in = (self._token_expires_on - self._token_created_on).total_seconds()
            return token['token']
1237901
function buildXOAuth2Token(user = '', token) {
  let authData = [`user=${user}`, `auth=Bearer ${token}`, '', ''];
  return (0, _emailjsBase.encode)(authData.join('\x01'));
}
1190456
function _getToken(opts, cb) {
    assert.string(opts.indexName, 'opts.indexName'); // used for error messages
    assert.string(opts.realm, 'opts.realm');
    assert.optionalString(opts.service, 'opts.service');
    assert.optionalArrayOfString(opts.scopes, 'opts.scopes');
    assert.optionalString(opts.username, 'opts.username');
    assert.optionalString(opts.password, 'opts.password');
    // HTTP client opts:
    assert.object(opts.log, 'opts.log');
    assert.optionalObject(opts.agent, 'opts.agent');
    // assert.optional object or bool(opts.proxy, 'opts.proxy');
    assert.optionalBool(opts.insecure, 'opts.insecure');
    assert.optionalString(opts.userAgent, 'opts.userAgent');
    var log = opts.log;

    // - add https:// prefix (or http) if none on 'realm'
    var tokenUrl = opts.realm;
    var match = /^(\w+):\/\//.exec(tokenUrl);
    if (!match) {
        tokenUrl = (opts.insecure ? 'http' : 'https') + '://' + tokenUrl;
    } else if (['http', 'https'].indexOf(match[1]) === -1) {
        return cb(new Error(fmt('unsupported scheme for ' +
            'WWW-Authenticate realm "%s": "%s"', opts.realm, match[1])));
    }

    // - GET $realm
    //      ?service=$service
    //      (&scope=$scope)*
    //      (&account=$username)
    //   Authorization: Basic ...
    var headers = {};
    var query = {};
    if (opts.service) {
        query.service = opts.service;
    }
    if (opts.scopes && opts.scopes.length) {
        query.scope = opts.scopes;  // intentionally singular 'scope'
    }

    if (opts.username) {
        query.account = opts.username;
        _setAuthHeaderFromAuthInfo(headers, {
            username: opts.username,
            password: opts.password
        });
    }
    if (Object.keys(query).length) {
        tokenUrl += '?' + querystring.stringify(query);
    }
    log.trace({tokenUrl: tokenUrl}, '_getToken: url');

    var parsedUrl = mod_url.parse(tokenUrl);
    var client = new DockerJsonClient({
        url: parsedUrl.protocol + '//' + parsedUrl.host,
        log: log,
        agent: opts.agent,
        proxy: opts.proxy,
        rejectUnauthorized: !opts.insecure,
        userAgent: opts.userAgent || common.DEFAULT_USERAGENT
    });
    client.get({
        path: parsedUrl.path,
        headers: headers
    }, function (err, req, res, body) {
        client.close();
        if (err) {
            if (err.statusCode === 401) {
                // Convert *all* 401 errors to use a generic error constructor
                // with a simple error message.
                var errMsg = _getRegistryErrorMessage(err);
                return cb(new errors.UnauthorizedError(errMsg));
            }
            return cb(err);
        } else if (!body.token) {
            return cb(new errors.UnauthorizedError(err, 'authorization ' +
                'server did not include a token in the response'));
        }
        cb(null, body.token);
    });
}
180958
def make_soap_enveloped_saml_thingy(thingy, header_parts=None):
    
    envelope = ElementTree.Element('')
    envelope.tag = '{%s}Envelope' % NAMESPACE

    if header_parts:
        header = ElementTree.Element('')
        header.tag = '{%s}Header' % NAMESPACE
        envelope.append(header)
        for part in header_parts:
            # This doesn't work if the headers are signed
            part.become_child_element_of(header)

    body = ElementTree.Element('')
    body.tag = '{%s}Body' % NAMESPACE
    envelope.append(body)

    if isinstance(thingy, six.string_types):
        # remove the first XML version/encoding line
        if thingy[0:5].lower() == '<?xml':
            logger.debug("thingy0: %s", thingy)
            _part = thingy.split("\n")
            thingy = "".join(_part[1:])
        thingy = thingy.replace(PREFIX, "")
        logger.debug("thingy: %s", thingy)
        _child = ElementTree.Element('')
        _child.tag = '{%s}FuddleMuddle' % DUMMY_NAMESPACE
        body.append(_child)
        _str = ElementTree.tostring(envelope, encoding="UTF-8")
        if isinstance(_str, six.binary_type):
            _str = _str.decode('utf-8')
        logger.debug("SOAP precursor: %s", _str)
        # find an remove the namespace definition
        i = _str.find(DUMMY_NAMESPACE)
        j = _str.rfind("xmlns:", 0, i)
        cut1 = _str[j:i + len(DUMMY_NAMESPACE) + 1]
        _str = _str.replace(cut1, "")
        first = _str.find("<%s:FuddleMuddle" % (cut1[6:9],))
        last = _str.find(">", first + 14)
        cut2 = _str[first:last + 1]
        return _str.replace(cut2, thingy)
    else:
        thingy.become_child_element_of(body)
        return ElementTree.tostring(envelope, encoding="UTF-8")
1253917
def dump_soap_request(service_url, request_xml)
      return unless @soap_dump
      %w{email password developerToken authToken clientEmail}.each do |tag|
        request_xml = request_xml.gsub(/<#{tag}([^>]*)>.*<\/#{tag}>/, "<#{tag}\\1>***censured***</#{tag}>")
      end
      str = ""
      str << "<!-- Post to '#{service_url}' -->\n"
      str << xml_to_s(request_xml) << "\n"
      dump(service_url, "req", str)
    end
1256907
function processToken(token, done) {
    var user = _.find(users, function (item) {
        return item.username === token[claims.username];
    });
    if (!user) {
        user = {
            id          : token[claims.id] || currId++,
            username    : token[claims.username],
            email       : token[claims.email],
            firstName   : token[claims.firstName],
            lastName    : token[claims.lastName]
        };
        var roles = token[claims.role];
        if (!roles) {
            roles = ["guest"];
        } else if (!(roles instanceof Array)) {
            roles = [roles];
        }
        user.roles = roles;
        users.push(user);
    }
    done(null, user);
}
399103
function write_ws_xml_protection(sp) {
	// algorithmName, hashValue, saltValue, spinCountpassword
	var o = ({sheet:1});
	var deffalse = ["objects", "scenarios", "selectLockedCells", "selectUnlockedCells"];
	var deftrue = [
		"formatColumns", "formatRows", "formatCells",
		"insertColumns", "insertRows", "insertHyperlinks",
		"deleteColumns", "deleteRows",
		"sort", "autoFilter", "pivotTables"
	];
	deffalse.forEach(function(n) { if(sp[n] != null && sp[n]) o[n] = "1"; });
	deftrue.forEach(function(n) { if(sp[n] != null && !sp[n]) o[n] = "0"; });
	/* TODO: algorithm */
	if(sp.password) o.password = crypto_CreatePasswordVerifier_Method1(sp.password).toString(16).toUpperCase();
	return writextag('sheetProtection', null, o);
}
1180254
void getTokensFromTokenEndpoint() throws SocialLoginException {
        try {
            tokens = getTokensUsingAuthzCode();
        } catch (Exception e) {
            throw createExceptionAndLogMessage(e, "AUTH_CODE_ERROR_GETTING_TOKENS", new Object[] { socialConfig.getUniqueId(), e.getLocalizedMessage() });
        }
    }
751231
function init(ctx) {
        var server = ctx.server;

        if (!privateKey) {
            throw new Error('Please set config.security.token.privateKey');
        }

        server.ext('onPreAuth', validateToken);

        return new Q(ctx);
    }
657701
def security_hash(namespace, tag, hash, extra_info = {})
      key = [namespace, tag].compact.join(":")

      sec_hash = {
        "wsse:Security" => {
          key => hash
        },
        :attributes! => { "wsse:Security" => { "xmlns:wsse" => WSE_NAMESPACE } }
      }

      unless extra_info.empty?
        sec_hash["wsse:Security"].merge!(extra_info)
      end

      if signature?
        sec_hash[:attributes!].merge!("soapenv:mustUnderstand" => "1")
      else
        sec_hash["wsse:Security"].merge!(:attributes! => { key => { "wsu:Id" => "#{tag}-#{count}", "xmlns:wsu" => WSU_NAMESPACE } })
      end

      sec_hash
    end
625156
public Mono<String> getUaaUrl() {
		this.uaaUrl = this.webClient.get().uri(this.cloudControllerUrl + "/info")
				.retrieve().bodyToMono(Map.class)
				.map((response) -> (String) response.get("token_endpoint")).cache()
				.onErrorMap((ex) -> new CloudFoundryAuthorizationException(
						Reason.SERVICE_UNAVAILABLE,
						"Unable to fetch token keys from UAA."));
		return this.uaaUrl;
	}
628706
function processSOAPNode(node, msgParams, msg) {
    // Handle simple generic SOAP. TBD: Handle multiple types of SOAP security and other params
    // TBD: Test Security features
    // TBD: Implement soap listen

    let options = {};
    console.log('Processing Node .......... ');
    console.log(JSON.stringify(node));
    let params = processValuesFromContext(node, msgParams, msg, [
      {name: 'url', type: 'urlType'},
      {name: 'method', type: 'methodType'},
      {name: 'parameters', type: 'parametersType'},
      {name: 'headers', type: 'headersType'},
    ]);
    console.log(params);


    soap.createClient(params.url, options, function(err, client) {
      if (err) {
        let errInvalidSOAP = util.format('Error while creating soap client - %s', err);
        msg.error = getError(node, errInvalidSOAP);
        node.error(errInvalidSOAP, msg);
        return;
      }
      try {
        let method = eval('client' + params.method);
        // let method = client['GetHolidaysAvailable'];
        // let requestArgs = {"countryCode": "UnitedStates"};
        method(params.parameters, function(err, result, envelope, soapHeader) {
          if (err) {
            let errInvalidSOAP = util.format('Error while calling soap service - %s', err);
            msg.error = getError(node, errInvalidSOAP);
            node.error(errInvalidSOAP, msg);
            return;
          }
          // response envelope
          console.log('Response Envelope: \n' + envelope);
          // 'result' is the response body
          console.log('Result: \n' + JSON.stringify(result));
          console.log(JSON.stringify(result));
          msg.payload = JSON.stringify(result);
          node.send(msg);
          return;
        });
      } catch (error) {
        let errInvalidSOAP = util.format('Error while calling soap service - %s', error);
        msg.error = getError(node, errInvalidSOAP);
        node.error(errInvalidSOAP, msg);
        return;
      }
    });
  }