How do i pick specific cookies? - paw-app

How can I select specific cookies from a response?
The response I'm getting has 6 Set-Cookie rows, but I just need some of them for my next post.
HTTP/1.1 200 OK
date: Thu, 05 Mar 2015 13:49:29 GMT
cache-control: no-cache="set-cookie, set-cookie2"
expires: Thu, 01 Dec 1994 16:00:00 GMT
Set-Cookie: JSESSIONID-AUTH=0000Q77IB2vtdMjRmqnsja8ciUE:18j7lq1fl;Secure; Path=/
Set-Cookie: PD_STATEFUL_e0255922-d1d6-11e3-9144-005056bc2960=%2Fnauth2;Secure; Path=/
Set-Cookie: PD-SESSION-ID=1_4_0_Mip9xQRE1J80beniD1eh-7Le1L+X8uwfIRVUZdKvJUKO2OIB;Secure; Path=/; HttpOnly
Set-Cookie: iampsc1110=rd520o00000000000000000000ffff0a101fa3o1110;secure; path=/
Set-Cookie: TSaee27a=e4d514b3ab1503842b07e9b4d4ee0db30a6a3a54c730b09754f85edbe54ca44a641b9f7bf3fdf509ca7d6de2ed2d4e69c8c3db3f6623dd16fb85456b4ced6f5a34c171e7a460affd34c171e70025563134c171e75f534b1f34c171e7; Path=/

You're right, there is no proper way to do this yet. Here are 2 workarounds:
Manually, you can go and delete the cookies you don't want. In the Requests menu, pick Cookies then Show Cookies. Use the search box to find the cookies you'd like to get rid of.
A more complex solution, but that exactly fits your need, I think. Use a Custom dynamic value (right click on the field, and pick Extensions > Custom), instead, and use the following JavaScript code snippet:
function evaluate(context){
// Set here the cookies you'd like to return
var wantedCookies = ["datr", "reg_fb_ref"];
var regex = /^(\w+)\=([^;\s]+)/g;
// Request
// Uses here the current request, you can use getRequestByName("name of the request") instead
var request = context.getCurrentRequest();
// Get response cookies
var cookies = request.getLastExchange().getResponseHeaderByName("Set-Cookie").split(", ");
var filteredCookies = [];
for (var i in cookies) {
var cookie = cookies[i];
var match = regex.exec(cookie);
if (match && wantedCookies.indexOf(match[1]) >= 0) {
filteredCookies.push(match[0]);
}
}
return filteredCookies.join(",");
};
That basically parses manually the response cookies, and returns the ones you need.

Related

Getting JSON Tag Value into a text field in ASP.NET

I need to get the "uxfauthorization" tag value into a text box in ASP.NET. I am using curl to send the json request to server and getting below response from the server. I want "uxfauthorization" key value to be in text box so that user can view the authorization key.
HTTP/1.1 200 OK
Cache-Control: no-cache, no-store, must-revalidate
Date: Tue, 08 Dec 2015 15:16:45 GMT
Pragma: no-cache
Content-Length: 22
Content-Type: application/json
Expires: -1
SET-COOKIE:WIRELESS_SECURITY_TOKEN=HvsvzzAyux0oXBENeLPwtQ**___currentencryptionkey___36wByp bpGkrOz/CQ6pTbGt44O+PpWvB0gu8hr12vIYa32j2Qg3Na3eylq5h4dZLeAmA6T6kZ4hevGJUjqXeFN8 2DIyEdaO7MVEqiemiGB90F7J0KXfiUdRjw5E5XkV9a; path=/; HttpOnly;
uxf_lastLoginDate: 1449587736928
uxfauthorization:UXF_CSRFToken:csrfcurrentencryptionkey___dpU+veeOOvcV/0mrZKt3V8c4tI677cvo0hodpmXppOQ= UXF_SessionToken:HvsvzzAyux0oXBENeLPwtQ==___currentencryptionkey___36wBypbpGkrOz/CQ6pTbGt44O+PpWvB0gu8hr12vIYa32j2Qg3Na3eylq5h4dZLeAmA6T6kZ4hevGJUjqXeFN82DIyEdaO7MVEqiemiGB90F7J0KXfiUdRjw5E5XkV9a
X-XSS-Protection: 1; mode=block
X-Powered-By: Servlet/3.0 JSP/2.2
{"__EmptyObject__":{}}
Thanks In Advance.
You can use regular expression to parse the value from the text. It can be something like below:
String pattern = #"uxfauthorization:(.*?)";
Regex re = new Regex(pattern);
MatchCollection matches = re.Matches(your_curl_response_here);
foreach(Match match in matches){
// use the match.ToString() for your need
}

Log in value from Set-Cookie header in nginx

Is it possible to write in nginx access log value of key 'uuid' from Cookie for server response (header: Set-Cookie)?
$cookie_uuid - return uuid that sent client
$sent_http_set_cookie - return whole header Set-Cookie: 'uuid=897587e7-a733-422f-9daa-b3105a5895aa; domain=domain.com; path=/; expires=Tue, 09-Aug-2033 01:17:54 GMT', but I need save only value for key 'uuid'
Thanks
map $sent_http_set_cookie $resp_uuid {
~*uuid=(?<u>[0-9a-f-]+) $u;
}
Reference:
http://nginx.org/r/map
man pcresyntax

MVC 3 client caching

I am trying to make modifications to an existing CDN. What I am trying to do is create a short cache time and use conditional GETs to see if the file has been updated.
I am tearing my hair out because even though I am setting a last modified date and seeing it in the response headers, on subsequent get requests I am not seeing an If-Modified-Since header being returned. At first I thought it was my local development environment or the fact that I was using Fiddler as a proxy for testing so I deployed to a QA server. But what I am seeing in Firebug is so different than what I am doing. I see the last modified date, for some reason it is setting my cache-control to private, and I have cleared any header Output Caching and the only header IIS 7.5 is set to write is to enable Http keep-alive, so all the caching should be driven by the code.
This seemed like such a no-brainer, yet I've been adding and removing headers all day with no luck. I checked global.asax and anywhere else (I didn't write the app so I was looking for any hidden surprises and am stumped. Below is the current code and request and response headers. I have the expiration set to 30 seconds just for testing purposes. I have looked at several samples, I don't see myself doing anything different, but it simply won't work.
Response Headersview source
Cache-Control private, max-age=30
Content-Length 597353
Content-Type image/jpg
Date Tue, 03 Sep 2013 21:33:55 GMT
Expires Tue, 03 Sep 2013 21:34:25 GMT
Last-Modified Tue, 03 Sep 2013 21:33:55 GMT
Server Microsoft-IIS/7.5
X-AspNet-Version 4.0.30319
X-AspNetMvc-Version 3.0
X-Powered-By ASP.NET
Request Headersview source
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Connection keep-alive
Cookie __utma=1.759556114.1354835397.1377631052.1377732484.36; __utmz=1.1354835397.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)
Host hqat4app1
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetLastModified(DateTime.Now);
return new FileContentResult(fileContents, contentType);
The relevant code is:
public ActionResult Resize(int id, int size, bool grayscale)
{
_logger.Debug(() => string.Format("Resize {0} {1} {2}", id, size, grayscale));
string imageFileName = null;
if (id > 0)
using (new UnitOfWorkScope())
imageFileName = RepositoryFactory.CreateReadOnly<Image>().Where(o => o.Id == id).Select(o => o.FileName).SingleOrDefault();
CacheImageSize(id, size);
if (!ImageWasModified(imageFileName))
{
Response.Cache.SetExpires(DateTime.Now.AddSeconds(30));
Response.StatusCode = (int)HttpStatusCode.NotModified;
Response.Status = "304 Not Modified";
return new HttpStatusCodeResult((int)HttpStatusCode.NotModified, "Not-Modified");
}
byte[] fileContents;
if (ShouldReturnDefaultImage(imageFileName))
fileContents = GetDefaultImageContents(size, grayscale);
else
{
bool foundImageFile;
fileContents = GetImageContents(id, size, grayscale, imageFileName, out foundImageFile);
if (!foundImageFile)
{
// No file found, clear cache, disable output cache
//ClearOutputAndRuntimeCacheForImage(id, grayscale);
//Response.DisableKernelCache();
}
}
string contentType = GetBestContentType(imageFileName);
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetLastModified(DateTime.Now);
return new FileContentResult(fileContents, contentType);
}
private bool ImageWasModified(string fileName)
{
bool foundImageFile;
string filePath = GetFileOrDefaultPath(fileName, out foundImageFile);
if (foundImageFile)
{
string header = Request.Headers["If-Modified-Since"];
if(!string.IsNullOrEmpty(header))
{
DateTime isModifiedSince;
if (DateTime.TryParse(header, out isModifiedSince))
{
return isModifiedSince < System.IO.File.GetLastWriteTime(filePath);
}
}
}
return true;
}

HttpClient request to local IIS 8.0 does not produce expected headers in the response

I'm making the following request to a local website running in IIS
var httpRequestMessage = new HttpRequestMessage();
httpRequestMessage.RequestUri = new Uri("http://localhost:8081/");
httpRequestMessage.Method = HttpMethod.Get;
var response = new HttpClient().SendAsync(httpRequestMessage).Result;
This produces the following response headers:
HTTP/1.1 200 OK
Accept-Ranges: bytes
Date: Mon, 03 Jun 2013 22:34:25 GMT
ETag: "50c7472eb342ce1:0"
Server: Microsoft-IIS/8.0
X-Powered-By: ASP.NET
An identical request made via Fiddler produces the following response headers (I've highlighted the differences):
HTTP/1.1 200 OK
Content-Type: text/html
Last-Modified: Fri, 26 Apr 2013 19:20:58 GMT
Accept-Ranges: bytes
ETag: "50c7472eb342ce1:0"
Server: Microsoft-IIS/8.0
X-Powered-By: ASP.NET
Date: Mon, 03 Jun 2013 22:29:34 GMT
Content-Length: 10
Why is there a difference in response headers?
Am I using HttpClient correctly (aside from the fact I am calling Send synchronously)?
TL;DR;
To access all response headers you need to read both HttpResponseMessage.Headers and HttpResponseMessage.Content.Headers properties.
Long(er) answer:
This, basically:
var response = new HttpClient().GetAsync("http://uri/").Result;
var allHeaders = response.Headers.Union(response.Content.Headers);
foreach (var header in allHeaders)
{
// do stuff
}
I see two issues with this:
The Headers property is not appropriately named: it should really be SomeHeaders or AllHeadersExceptContentHeaders. (I mean, really, when you see a property named Headers, do you expect it to return all headers or some headers? I am pretty sure they are in violation of their own framework design guidelines on this one.)
The MSDN page does not mention at any point the fact this is a subset of all headers and developers should also inspect Content.Headers.

OutputCache is sending wrong Vary header when the call hits the cache

I have an action method that I want to cache:
[OutputCache(Duration=60*5, Location=OutputCacheLocation.Any, VaryByCustom="index")]
public ActionResult Index()
{
return View();
}
With this approach:
public override string GetVaryByCustomString(HttpContext context, string custom)
{
context.Response.Cache.SetOmitVaryStar(true);
context.Response.Cache.VaryByHeaders["Cookie"] = true;
if (User.Identity.IsAuthenticated)
{
Debug.Print("Authenticated");
context.Response.Cache.SetNoServerCaching();
context.Response.Cache.SetCacheability(HttpCacheability.Private);
return null;
}
else
{
Debug.Print("Non authenticated");
return custom;
}
}
The idea was to keep a cached version of the page for non-authenticated users, but avoid caching for authenticated ones.
I thought it will always return a Vary:Cookie HTTP header, but it is not.
Doing a test with Fiddler and issuing twice the same request, in the first HTTP call it goes good:
HTTP/1.1 200 OK
Cache-Control: public, max-age=300
Content-Type: text/html; charset=utf-8
Expires: Thu, 09 Feb 2012 10:53:36 GMT
Last-Modified: Thu, 09 Feb 2012 10:48:36 GMT
Vary: Cookie
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 3.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 09 Feb 2012 10:48:37 GMT
Content-Length: 441
But in the second one, it overwrites the header:
HTTP/1.1 200 OK
Cache-Control: public, max-age=297
Content-Type: text/html; charset=utf-8
Expires: Thu, 09 Feb 2012 10:53:36 GMT
Last-Modified: Thu, 09 Feb 2012 10:48:36 GMT
Vary: *
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 3.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 09 Feb 2012 10:48:39 GMT
Content-Length: 441
So, as far as I know, browsers won't cache the request even if it is public, since Vary:* means that the request has been generated with parameters that are not in the URL nor in the HTTP headers. Is there a way to fix this?
Regards.
UPDATE:
In a similar way, when I send two identical authenticated requests, the first call gets the private modifier, but not the Vary header:
HTTP/1.1 200 OK
Cache-Control: private, max-age=300
Content-Type: text/html; charset=utf-8
Expires: Thu, 09 Feb 2012 12:43:14 GMT
Last-Modified: Thu, 09 Feb 2012 12:38:14 GMT
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 3.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 09 Feb 2012 12:38:14 GMT
Content-Length: 443
But the second one gets the same response that a non-authenticated request:
HTTP/1.1 200 OK
Cache-Control: public, max-age=298
Content-Type: text/html; charset=utf-8
Expires: Thu, 09 Feb 2012 12:44:32 GMT
Last-Modified: Thu, 09 Feb 2012 12:39:32 GMT
Vary: *
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 3.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 09 Feb 2012 12:39:33 GMT
Content-Length: 443
I have uploaded a test project showing the issue so may be you want to give it a try.
Please be aware that there is an IHttpModule that sets a request as authenticated or not depending on if the request has a cookie or not, this is not a "real life" approach, it is just for testing purposes.
The project contains only a web page with a link to itself, a link that logs you in, and another link that logs you out:
LogIn : Sends a cookie in a HTTP 302 redirection to the home page again.
LogOut: Sends a expired cookie in a HTTP 302 recirection to the home page again.
The expected/ideal behaviour would be:
User access Index, and get the page from the server. The page show date "A".
User access Index again, and the browser shows the cached version.The page show date "A".
Clean browser cache.
User access Index again, and the browser shows the server cached version. The page show date "A".
User clicks login, and the broswer gets a new page, that show date "B".
User clicks logout, and the browser gets the server cached page. The page show date "A" again.
But this is the behaviour so far:
User access Index, and get the page from the server. The page show date "A".
User access Index again, and the browser shows the cached version.The page show date "A".
Clean browser cache.
User access Index again, and the browser shows the server cached version. The page show date "A".
User clicks login, and the broswer gets a new page, that show date "B".
User clicks logout, and the browser should get the server cached page, but it does not. The page show date "B" again from the browser cache. This is because the lack of the Vary header in the authenticated response.
I don't know if I get something wrong about caching, just missing some detail or the OutputCache does not work very well, but I would appreciate any guidance.
Cheers.
UPDATE 2:
My intention is to use the HTTP cache semantics to:
Allow browsers and proxys to cache the "public" version of the page.
Allow browsers to cache the "authenticated" version of the page for its user.
If I change the OutputCache declaration to do the caching only on the server and prevent the downstream and client caching:
[OutputCache(Duration=60*5, Location=OutputCacheLocation.Server, VaryByCustom="index")]
it behaves as expected, but the downstream and client cache is prevented, and that is not what I want.
I don't think the [OutputCache] attribute is what you want, the VaryByCustom method is basically saying that I want to cache different versions based on these parameters, it doesn't really have an option for Do Not Cache and the majority of the code in the attribute is built around server based caching.
That being said the documentation on MSDN for custom caching seems to indicate you need to return a string to vary on based on the authentication state:
public override string GetVaryByCustomString(HttpContext context, string custom)
{
if(custom == "user") return "User:" + context.Request.User.Identity.Name;
return base.GetVaryByCustomString(context, custom);
}
And then use the user literal in the VaryByCustom:
[OutputCache(Duration=60*5, Location=OutputCacheLocation.Any, VaryByCustom="user")]
public ActionResult Index()
{
return View();
}
So basically this would result in a cache being built for anonymous (assuming the anonymous identity is empty string or something) and every user on the server, and a Vary: * sent to the client I believe. Obviously not ideal what you are looking for.
If you really just want to cache the unauthenticated version using HTTP caching I would recommend not using the OutputCacheAttribute and using something more custom.
You could easily just write in your own custom attribute something like what you have for your GetVaryByCustomString implementation (this is just some pseudo code, would need more than this):
public class HttpCacheUnauthenticatedAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if(!filterContext.HttpContext.Request.IsAuthenticated) {
//TODO: set unauthenticated caching values and vary here
}
}
}
And then tag your action method with it:
[HttpCacheUnauthenticated]
public ActionResult Index()
{
return View();
}
Sort of wrestling with something similar myself. Have you tried in the web.config to the setting omitVaryStar=true
https://msdn.microsoft.com/en-us/library/ms228124(v=vs.100).aspx
I am using a custom cache provider and in this case there is a simple solution for this.
On the BeginRequest, based on the user authentication status, we set a context information to not run cache:
HttpContext.Current.Items["NoCache"] = "1";
And then on our GetVaryBy method we return null if this information is set:
public override string GetVaryByCustomString(HttpContext context, string custom)
{
if (HttpContext.Current.Items["NoCache"] != null)
return null;
// remaining code here
}
And then on the cache methods, we can test the same. For instance:
public override object Add(string key, object entry, DateTime utcExpiry)
{
if (HttpContext.Current.Items["NoCache"] != null)
return null;
// remaining code here
}

Resources