Set the token secret on the request.

@param {IncomingMessage} req
@param {OutgoingMessage} res
@param {string} sessionKey
@param {string} val
@param {Object} [cookie]
@api private
761745
function setSecret (req, res, sessionKey, val, cookie) {
  if (cookie) {
    // set secret on cookie
    var value = val

    if (cookie.signed) {
      value = 's:' + sign(val, req.secret)
    }

    setCookie(res, cookie.key, value, cookie)
  } else {
    // set secret on session
    req[sessionKey].csrfSecret = val
  }
}
688159
function(req, res, user) {
    var jsonWebTokens = waterlock.config.jsonWebTokens || {};
    var expiryUnit = (jsonWebTokens.expiry && jsonWebTokens.expiry.unit) || 'days';
    var expiryLength = (jsonWebTokens.expiry && jsonWebTokens.expiry.length) || 7;
    var expires = moment().add(expiryLength, expiryUnit).valueOf();
    var issued = Date.now();
    user = user || req.session.user;

    var token = jwt.encode({
      iss: user.id + '|' + req.remoteAddress,
      sub: jsonWebTokens.subject,
      aud: jsonWebTokens.audience,
      exp: expires,
      nbf: issued,
      iat: issued,
      jti: uuid.v1()
    }, jsonWebTokens.secret);

    return {
      token: token,
      expires: expires
    };
  }
247575
async function( req, res, next ) {
    try { 
      var csrfToken = 'default'
      if ( req.cookies && req.cookies[ 'pong-security' ] ) {
        var token = req.cookies[ 'pong-security' ]
        if ( gui.getCsrfTokenForUser ) {
          csrfToken = await gui.getCsrfTokenForUser( token )
        } else if ( gui.userTokens[ token ] && gui.userTokens[ token ].csrfToken ) {
          csrfToken = gui.userTokens[ token ].csrfToken
        }
      }
    } catch ( exc ) { log.warn('easy-web-app CSRF token, exc') }
    res.header( 'X-Protect', csrfToken );
    next();
  }
644060
function sessionDecorator() {
    // save token header to be used in cookieParserDecorator middleware.
    tokenHeaderName = rs.keystone.get('resty token header');

    rs.keystone.session = RestySession.factory(rs.keystone);
    rs.keystone.set('session', rs.keystone.session.persist);
}
362484
function shouldSetCookie(req) {
      // cannot set cookie without a session ID
      if (typeof req.sessionID !== 'string') {
        return false;
      }

      return cookieId !== req.sessionID
        ? saveUninitializedSession || isModified(req.session)
        : rollingSessions || req.session.cookie.expires != null && isModified(req.session);
    }
292515
protected void setSessionCookie(HttpServerExchange exchange) {
        Session session = this.attachment.getSession();
        if (session.isInvalid()) {
            Cookie cookie = new CookieImpl(this.config.getSessionCookieName())
                    .setSecure(this.config.isSessionCookieSecure())
                    .setHttpOnly(true)
                    .setPath("/")
                    .setMaxAge(0)
                    .setSameSite(true)
                    .setSameSiteMode(SAME_SITE_MODE)
                    .setDiscard(true);
            
            exchange.setResponseCookie(cookie);
        } else if (session.hasChanges()) {
            JwtClaims jwtClaims = new JwtClaims();
            jwtClaims.setClaim(ClaimKey.AUTHENTICITY.toString(), session.getAuthenticity());
            jwtClaims.setClaim(ClaimKey.DATA.toString(), session.getValues());
            
            if (session.getExpires() == null) {
                jwtClaims.setClaim(ClaimKey.EXPIRES.toString(), "-1");
            } else {
                jwtClaims.setClaim(ClaimKey.EXPIRES.toString(), session.getExpires().format(DateUtils.formatter));        
            }
            
            JsonWebSignature jsonWebSignature = new JsonWebSignature();
            jsonWebSignature.setKey(new HmacKey(this.config.getSessionCookieSignKey().getBytes(StandardCharsets.UTF_8)));
            jsonWebSignature.setPayload(jwtClaims.toJson());
            jsonWebSignature.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA512);
            
            try {
                String encryptedValue = Application.getInstance(Crypto.class).encrypt(jsonWebSignature.getCompactSerialization(), this.config.getSessionCookieEncryptionKey());
                Cookie cookie = new CookieImpl(this.config.getSessionCookieName())
                        .setValue(encryptedValue)
                        .setSameSite(true)
                        .setSameSiteMode(SAME_SITE_MODE)
                        .setHttpOnly(true)
                        .setPath("/")
                        .setSecure(this.config.isSessionCookieSecure());
                
                if (session.getExpires() != null) {
                    cookie.setExpires(DateUtils.localDateTimeToDate(session.getExpires()));
                }

                exchange.setResponseCookie(cookie);
            } catch (Exception e) { //NOSONAR Intentionally catching exception here
                LOG.error("Failed to generate session cookie", e);
            }
        } else {
            //Ignore and send no cookie to the client
        }
    }
784469
function set(req, res) {
  var key = '' + req.args[0]
    , value = req.args[1];

  // already validated the config key/value so should be ok
  // to update the in-memory config, some config verification
  // methods perform side-effects, eg: dir
  this.conf.set(key, value);
  res.send(null, Constants.OK);
  if(key === ConfigKey.DIR) {
    this.log.notice('cwd: %s', process.cwd());
  }
}
375782
@SuppressWarnings("rawtypes")
	private void restoreFromCookie(IExtendedRequest extRequest, HttpServletResponse res, String reqURL) {
		byte[] cookieValueBytes = extRequest.getCookieValueAsBytes(POSTPARAM_COOKIE);
		if (cookieValueBytes == null || cookieValueBytes.length <= 2) {
			return;
		}
		if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
			Tr.debug(tc, "Found the cookie, restoring POST parameters: " + new String(cookieValueBytes));
		}
		try {
			HashMap restoredParams = deserializePostParam(extRequest, cookieValueBytes, reqURL);
			extRequest.setInputStreamData(restoredParams);
			extRequest.setMethod("POST");
		} catch (Exception e) {
			if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
				Tr.debug(tc, "Exception restoring POST parameters from the cookie: ", new Object[] { e });
			}
		}
		Cookie paramCookie = new Cookie(POSTPARAM_COOKIE, "");
		paramCookie.setPath(reqURL);
		paramCookie.setMaxAge(0);
		if (webAppSecurityConfig.getHttpOnlyCookies()) {
			paramCookie.setHttpOnly(true);
		}
		if (webAppSecurityConfig.getSSORequiresSSL()) {
			paramCookie.setSecure(true);
		}
		res.addCookie(paramCookie);
	}
378073
function (req, res) {
    var redirectTo = req.cookies.oauthRedirectUri || false;

    if (redirectTo) {
      res.clearCookie('oauthRedirectUri');
    }

    return redirectTo;
  }
550278
function (user_id, cookie, passphrase, callback) {
		var packed_user_id = String.fromCharCode(0, 0, 0, 0, user_id >> 24 & 0xFF, user_id >> 16 & 0xFF, user_id >> 8 & 0xFF, user_id & 0xFF);
		var client_nonce = "";
		for (var i = 0; i < 16; ++i) {
			client_nonce += String.fromCharCode(Math.random() * 256);
		}
		var seed = packed_user_id + unescape(encodeURIComponent(passphrase));
		var data = packed_user_id + _server_nonce + client_nonce;
		var d = ecp.mpn_pack(util.hash_string_to_words(seed));
		var z = ecp.mpn_pack(util.hash_string_to_words(data));
		var r = ecp.mpn_new(8), s = ecp.mpn_new(8);
		ecp.ecp_sign(r, s, ecp.secp224k1_p, ecp.secp224k1_a, ecp.secp224k1_G, ecp.secp224k1_n, d, z, 8);
		request({
			method: "Authenticate",
			user_id: user_id,
			cookie: cookie,
			nonce: btoa(client_nonce),
			signature: [ btoa(util.words_to_string(ecp.mpn_unpack(r))), btoa(util.words_to_string(ecp.mpn_unpack(s))) ],
		}, callback);
	}
168871
@Override
    public void addSSOCookiesToResponse(Subject subject, HttpServletRequest req, HttpServletResponse resp) {
        if (!allowToAddCookieToResponse(req))
            return;

        addJwtSsoCookiesToResponse(subject, req, resp);

        if (!JwtSSOTokenHelper.shouldAlsoIncludeLtpaCookie()) {
            return;
        }

        SingleSignonToken ssoToken = getDefaultSSOTokenFromSubject(subject);
        if (ssoToken == null) {
            return;
        }

        byte[] ssoTokenBytes = ssoToken.getBytes();
        if (ssoTokenBytes == null) {
            return;
        }

        ByteArray cookieBytes = new ByteArray(ssoTokenBytes);
        String cookieByteString = cookieByteStringCache.get(cookieBytes);
        if (cookieByteString == null) {
            cookieByteString = StringUtil.toString(Base64Coder.base64Encode(ssoTokenBytes));
            updateCookieCache(cookieBytes, cookieByteString);
        }

        Cookie ssoCookie = createCookie(req, cookieByteString);
        resp.addCookie(ssoCookie);
    }
6321
function(req, res) {
    var params = URL.parse(req.url, true).query
      , code = params.code
      , state = params.state
    ;

    if(!code) {
      res.writeHead(400, {'Content-Type': 'text/plain'});
      return res.end('The "code" parameter is missing.');
    }
    if(!state) {
      res.writeHead(400, {'Content-Type': 'text/plain'});
      return res.end('The "state" parameter is missing.');
    }
    try {
      state = this.serializer.parse(state);
    } catch(err) {
      res.writeHead(400, {'Content-Type': 'text/plain'});
      return res.end('The "state" parameter is invalid.');
    }
    var data = {
      oauth2_server_id: state[0]
      , next_url: state[1]
      , state: state[2]
    }
    var methods = this.methods[data.oauth2_server_id];
    methods.valid_grant(data, code, function(err, token) {
      if (err) return server_error(res, err);
      if(!token) {
        res.writeHead(400, {'Content-Type': 'text/plain'});
        res.end('Invalid grant.');
        return;
      }
      data.token = token;
      methods.treat_access_token(data, req, res, function() {
        redirect(res, data.next_url);
      }, function(err){server_error(res, err)});
    });
  }
1128215
function kandado (secret) {
  // Default Options
  let config = {
    // Token Expiration
    tokenExpiration: '24h',
    // Require Token middleware
    requireToken (req, res, next) {
      res.json({ 'error': 'token_required' })
    },
    // Failed Authentication middleware
    failedAuth (req, res, next) {
      res.json({ 'error': 'token_invalid' })
    }
  }

  return {
    // Config setter
    set (key, value) {
      config[key] = value
    },
    // Config getter (just in-case you need it)
    get (key) {
      return config[key]
    },
    // Token Generator
    generateToken (data, tokenOptions = {}) {
      // Default Token Options
      tokenOptions.expiresIn = config.tokenExpiration

      return new Promise((resolve, reject) => {
        // Encrypt `data` using the given `secret` key
        jwt.sign(data, secret, tokenOptions, (err, token) => {
          if (err) reject(err)
          else resolve(token)
        })
      })
    },
    // Authentication Middleware
    required (req, res, next) {
      // Check GET (req.query) or POST (req.body) data for the 'token' key
      let token = req.query.token || req.body.token || req.headers.authorization

      if (!token) {
        // If no token was passed, proceed to 'requireToken' middleware
        config.requireToken(req, res, next)
      } else {
        // Else, verify 'token' using the given `secret` key
        jwt.verify(token, secret, (err, data) => {
          if (err) {
            // If token is invalid, pass `err` data to `req.authError`...
            req.authError = err
            // then proceed to `failedAuth` middleware
            config.failedAuth(req, res, next)
          } else {
            // Else if token is valid, pass decrypted `data` to `req.authData`...
            req.authData = data
            // then proceed to the next middleware or router callback
            next()
          }
        })
      }
    }
  }
}
274480
public static void invalidateReferrerURLCookie(HttpServletRequest req, HttpServletResponse res, String cookieName) {
        // 240540 getReferrerURLCookieHandler().invalidateReferrerURLCookie(req, res, cookieName); // need to have domain here too
        if (cookieName == null || req == null || res == null) {
            if (tc.isDebugEnabled()) {
                Tr.debug(tc, "invalidateReferrerURLCookie param is null, return");
            }
            return;
        }
        Cookie c = createCookie(cookieName, "", req);
        String domainName = getSsoDomain(req);
        if (domainName != null && !domainName.isEmpty()) {
            c.setDomain(domainName);
        }
        c.setMaxAge(0);
        res.addCookie(c);
    }
14515
function(req, res) {

      req.session.authenticated = false;

      var defaultString = 'You have successfully logged out.';

      // now respond or redirect
      var postResponse = this._resolvePostAction(waterlock.config.postActions.logout.success,
        defaultString);

      if (typeof postResponse === 'string' && this._isURI(postResponse)) {
        res.redirect(postResponse);
      } else {
        res.ok(postResponse);
      }
    }
1120895
function getCookieToken(res) {
		var value = res.req.cookies[cookieName(res.req)];
		if (!value)
			return false;

		var parts = value.split('|');

		// If the existing cookie is invalid, reject it.
		if (parts.length !== 3)
			return false;

		// If the user data doesn't match this request's user, reject the cookie
		if (parts[1] !== getUserData(res.req))
			return false;

		var hasher = crypto.createHmac(options.algorithm, cookieKey);
		hasher.update(parts[0]);
		hasher.update("|");	// Don't confuse longer or shorter userDatas
		hasher.update(parts[1]);

		// If the hash doesn't match, reject the cookie
		if (parts[2] !== hasher.digest('base64'))
			return false;

		return parts[0];
	}
605973
function(callback) {
        if (res.parsedHeader.payload.mode === 'handshake') {
          res.session = {
            sid: reqSid,
            cert: senderCert,
            token: reqToken
          };
          callback(null);
        } else {
          var querySid;
          if (sessionStore instanceof Store || 'undefined' !== typeof window) {
            querySid = my.config.urlBase;
          } else {
            querySid = reqSid;
          }
          // load the session if exists
          sessionStore.load(querySid, function(err, session){
            if (err) {
              callback(err);
            } else if (session) {
              log.debug('%s loaded session', app.name);
              log.debug(session);
              res.session = session;
              callback(null);
            } else {
              callback('session expired');
            }
          });
        }
      }