I've this behaviour of vcl_deliver, it removes every http.set-cookie from backend.
This is my piece of varnishlog:
- VCL_call DELIVER
- RespUnset Set-Cookie: JSESSIONID=20E1512F59F3BA8A7BAE6AC2C10B0F66; Path=/; HttpOnly
- RespUnset Set-Cookie: OpenCmsOuFqn=/; Expires=Wed, 03-Feb-2016 13:18:41 GMT; Path=/
- RespUnset Set-Cookie: OpenCmsUserName=Admin; Expires=Wed, 03-Feb-2016 13:18:41 GMT; Path=/
- RespHeader Set-Cookie: LB=fep001; path=/;
- RespHeader X-Cache: MISS
- VCL_return deliver
I may not see the configuration mistake I post it too.
This is my default.vcl config file:
vcl 4.0;
import std;
import directors;
backend fep001 {
.host = "fe1";
.port = "82";
.probe = {
.url = "/ping";
.interval = 10s;
.timeout = 1s;
.window = 1;
.threshold = 1;
.expected_response = 200;
}
}
backend fep002 {
.host = "fe2";
.port = "82";
.probe = {
.url = "/ping";
.interval = 10s;
.timeout = 1s;
.window = 1;
.threshold = 1;
.expected_response = 200;
}
}
sub vcl_init {
new cluster = directors.round_robin();
new clusterhash = directors.hash();
cluster.add_backend(fep001);
clusterhash.add_backend(fep001, 1.0);
cluster.add_backend(fep002);
clusterhash.add_backend(fep002, 1.0);
}
sub vcl_recv {
if (req.http.Cookie ~ "LB=fep[0-9]+") {
set req.backend_hint = clusterhash.backend(req.http.Cookie.LB);
} else {
set req.backend_hint = cluster.backend();
}
if (! std.healthy(req.backend_hint)) {
std.log("not healthy");
set req.backend_hint = cluster.backend();
}
if (req.http.Cookie) {
set req.http.Cookie = regsuball(req.http.Cookie, "(^|; ) *LB=[^;]+;? *", "\1");
}
if (req.method != "GET" && req.method != "HEAD") {
return(pass);
}
if (req.url ~ "^/export/.*$") {
return(hash);
}
return(pass);
}
sub vcl_backend_response {
set beresp.http.X-node = beresp.backend.name;
set beresp.http.Vary = "Accept-Encoding";
if (bereq.url ~ "^/export/.*$" && beresp.status < 400) {
set beresp.ttl = 30m;
} else {
set beresp.ttl = 0s;
}
return(deliver);
}
sub vcl_deliver {
if (obj.hits == 0 && req.http.Cookie !~ "LB=fep[0-9]+") {
set resp.http.Set-Cookie = "LB=" + resp.http.X-node + "; path=/;";
}
if (obj.hits > 0) {
set resp.http.X-Cache = "HIT:" + obj.hits;
} else {
set resp.http.X-Cache = "MISS";
}
}
How could I keep those http headers?
Thank you
Davide
I finally found one solution deduced from the article Proper sticky session load balancing in Varnish
It seems that Varnish 4 does not add other Set-Cookie but override it and does not add such Varnish 3 in such ways:
set resp.http.Set-Cookie = "LB=" + req.http.X-node + "; path=/;" + resp.http.Cookie;
It means that you have to use some VMODs.
I added cookie and header imports:
vcl 4.0;
import std;
import directors;
import cookie;
import header;
I changed a bit the backend selection:
cookie.parse(req.http.cookie);
if (cookie.get("LB")) {
set req.backend_hint = clusterhash.backend(cookie.get("LB"));
} else {
set req.backend_hint = cluster.backend();
}
if (! std.healthy(req.backend_hint)) {
std.log("not healthy");
set req.backend_hint = cluster.backend();
}
and in the end this is the main reason to add those VMODs:
if (obj.hits == 0 && req.http.Cookie !~ "LB=fep[0-9]+") {
header.remove(resp.http.Set-Cookie,"^LB=.*$");
header.append(resp.http.Set-Cookie,"LB=" + resp.http.X-node + "; Expires=" + cookie.format_rfc1123(now, 60m) + "; path=/;");
}
I hope this answer will help someone.
Related
I try to use following code to delete all cookies in page unload event. However it doesn't seem to work in Chrome. Is there a better way to do it?
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var chip = cookies[i],
entry = chip.split("="),
name = entry[0];
document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT; domain=' + window.location.hostname + '; path=/ ';
}
From another post I got a hint. The cookies I want to delete has Host only flag. Therefore I can not set domain when I write cookie back. Here is a working copy.
ar cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var chip = cookies[i],
entry = chip.split("="),
name = entry[0];
document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/ ';
}
My objective is to protect an aws s3 bucket link and I'm trying to solve this by using cloudfront as the link via which the s3 buckets are accessible, hence when a user tries to access the cloudfront link, there is a basic auth if there's no cookie in their browser, but if there's a cookie, then auth values in this cookie is checked and user is granted access.
PS: This is not a website, my quest is to protect s3 bucket links.
Here is my attempt, using lambda#edge, on viewer request, there's the auth page if user is not logged in, otherwise, they're allowed access, it works but I can't set cookies, because somewhere in aws documentation, cloudfront deletes set-cookies in header files: CloudFront removes the Cookie header from requests that it forwards to your origin and removes the Set-Cookie header from responses that it returns to your viewers
Here is my code:
'use strict';
// returns a response error
const responseError = {
status: '401',
statusDescription: 'Unauthorized',
headers: {
'www-authenticate': [{key: 'WWW-Authenticate', value:'Basic'}]
}
};
exports.handler = (event, context, callback) => {
// Get request and request headers
console.log(event.Records[0]);
const request = event.Records[0].cf.request;
const response = event.Records[0].cf.response;
const headers = request.headers;
// checks to see if headers exists with cookies
let hasTheHeader = (request, headerKey) => {
if (request.headers[headerKey]) {
return true;
}
else return false;
};
// Add set-cookie header to origin response
const setCookie = function(response, cookie) {
const cookieValue = `${cookie}`;
console.log(`Setting cookie ${cookieValue}`);
response.headers['set-cookie'] = [{ key: "Set-Cookie", value: cookieValue }];
}
// Configure authentication
const authUser = 'someuser';
const authPass = 'testpassword';
let authToken;
let authString;
// Construct the Auth string
const buff = new Buffer(authUser + ':' + authPass).toString('base64');
authString = 'Basic ' + buff;
const authCookie = 'testAuthToken';
//execute this on viewer request that is if request type is viewer request:
if(event.Records[0].cf.config.eventType == 'viewer-request'){
//check if cookies exists and assign authToken if it does not
if(hasTheHeader(request, 'cookie') ){
for (let i = 0; i < headers.cookie.length; i++)
{
if (headers.cookie[i].value.indexOf(authString) >= 0)
{
authToken = authString;
console.log(authToken);
break;
}
}
}
if (!authToken)
{
if (headers && headers.authorization && headers.authorization[0].value === authString)
{
// Set-Cookie: testAuthToken= new Buffer(authUser + ':' + authPass).toString('base64')
authToken = authString;
request.header.cookie = [];
//put cookie value to custom header - format is important
request.headers.cookie.push({'key': 'Cookie', 'value': authString});
}
else
{
callback(null, responseError);
}
// continue forwarding request
callback(null, request);
}
else{
//strip out "Basic " to extract Basic credential in base 64
var authInfo = authToken.slice(6);
var userCredentials = new Buffer(authInfo, 'base64');
var userLoginNamePass = userCredentials.toString();
var baseCredentials = userLoginNamePass.split(":");
var username = baseCredentials[0];
var userPass = baseCredentials[1];
if (username != authUser && userPass != authPass) {
//user auth failed
callback(null, responseError);
} else {
request.header.cookie = [];
//put cookie value to custom header - format is important
request.headers.cookie.push({'key': 'Cookie', 'value': authString});
}
// continue forwarding request
callback(null, request);
}
}
else if(event.Records[0].cf.config.eventType == 'origin-response')
{
if(hasTheHeader(request, 'cookie')){
for (let i = 0; i < headers.cookie.length; i++)
{
if (headers.cookie[i].value.indexOf(authString) >= 0)
{
setCookie(response, authString);
break;
}
}
}
// console.log(res_headers);
console.log("response: " + JSON.stringify(response));
callback(null, response);
}
};
Your suggestions will be most welcome. Thanks in advance.
Im using the google translate code on my page and it works good, but if I look at the cookie it says that it only have expiration during the session!? So I want to set it so it does´t expire, so that it is the same language when the user comes back as he choosed the first time.
Im using this now.
SOLVED! OK so with this the user can select a language and the next time he visit the page it is translated to the language he picked before!
var ckDomain;
function googleTranslateElementInit() {
function getCookie(name)
{
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
var kakan;
var googkakan;
kakan=getCookie("googtrans22");
$$(document).on('change', '#google_translate_element', function (e) {
setTimeout(function(){
function getCookie(name)
{
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
googkakan=getCookie("googtrans");
document.cookie = "googtrans22="+googkakan+"; expires=Thu, 07-Mar-2047 20:22:40 GMT; path=/" + ckDomain;
document.cookie = "googtrans22="+googkakan+"; expires=Thu, 07-Mar-2047 20:22:40 GMT; path=/";
},1000);
});
for (var ckDomain = window.location.hostname.split("."); 2 < ckDomain.length;){
ckDomain.shift();
}
ckDomain = ";domain=" + ckDomain.join(".");
// domain cookie
document.cookie = "googtrans="+kakan+"; expires=Thu, 07-Mar-2047 20:22:40 GMT; path=/" + ckDomain;
// host-only cookie (with no domain name definition)
document.cookie = "googtrans="+kakan+"; expires=Thu, 07-Mar-2047 20:22:40 GMT; path=/";
new google.translate.TranslateElement({
pageLanguage: 'sv',
autoDisplay: false,
layout: google.translate.TranslateElement
}, 'google_translate_element');
}
(function() {
var googleTranslateScript = document.createElement('script');
googleTranslateScript.type = 'text/javascript';
googleTranslateScript.async = true;
googleTranslateScript.src = 'https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit';
( document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0] ).appendChild( googleTranslateScript );
})();
Apparently the library is forced to write over the cookie to make it expire at end of the session.
The good news is that before doing that it reads the existing cookie, so you can feed it before each initialization call.
To force the library to translate a Swedish page into English:
function googleTranslateElementInit() {
var ckDomain;
for (var ckDomain = window.location.hostname.split("."); 2 < ckDomain.length;){
ckDomain.shift();
}
ckDomain = ";domain=" + ckDomain.join(".");
// domain cookie
document.cookie = "googtrans=/sv/en; expires=Thu, 07-Mar-2047 20:22:40 GMT; path=/" + ckDomain;
// host-only cookie (with no domain name definition)
document.cookie = "googtrans=/sv/en; expires=Thu, 07-Mar-2047 20:22:40 GMT; path=/";
new google.translate.TranslateElement({
pageLanguage: 'sv',
autoDisplay: false,
layout: google.translate.TranslateElement
}, 'google_translate_element');
}
Is it possible to read a cookie value in portal_normal.vm in Liferay 6.2?
You can use the cookie access method from the request:
#set($previousWeb = "...")
#foreach($cookie in $request.getCookies())
#if ($cookie.getName() eq "web")
#set($previousWeb = $cookie.getValue())
#end
#end
you can also do it using javaScript in portal_normal.vm
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
Goto javaScript cookie
I am already using this code add and delete in the cookies
deleted code:
String profileScore=null;
Cookie cookiesScore =new Cookie("profileScore","");
cookiesScore.setValue("");
cookiesScore.setMaxAge(0);
response.addCookie(cookiesScore);
but its not deleted properly please help me give any example
Try this if using javascript
create a cookie:
call a this method at login:
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
delete a cookie:
call a this method at logout:
function deleteCookies() {
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var eqPos = cookie.indexOf("=");
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
}