cookie set in DRF not coming over in request - cookies

my site is shofitv.com
I have my backend sending cookies over so users may access a protected cloudFront Distro.
The cookies are being generated fine.
They are being set but when I check my cookies via inspect element in my cookie tab I see none of my cookies present.
here is my code
def generate_signed_cookies(resource,expire_minutes, payload):
"""
#resource path to s3 object inside bucket(or a wildcard path,e.g. '/blah/*' or '*')
#expire_minutes how many minutes before we expire these access credentials (within cookie)
return tuple of domain used in resource URL & dict of name=>value cookies
"""
if not resource:
resource = '*'
dist_id = DOWNLOAD_DIST_ID
conn = CloudFrontConnection(AWS_ACCESS_KEY, AWS_SECRET_KEY)
dist = SignedCookiedCloudfrontDistribution(conn,dist_id)
cookies = dist.create_signed_cookies(resource,expire_minutes=expire_minutes)
taco = HttpResponse(json.dumps(payload), content_type="application/json")
taco.set_cookie('CloudFront-Policy', cookies[1]['CloudFront-Policy'], httponly=False, domain="shofitv.com")
taco.set_cookie('CloudFront-Signature', cookies[1]['CloudFront-Signature'],
httponly=False, domain="shofitv.com")
taco.set_cookie('CloudFront-Key-Pair-Id', cookies[1]['CloudFront-Key-Pair-Id'],
httponly=False, domain="shofitv.com")
print('here is the taco')
print(taco)
return taco
again you wont see cloudFront-Policy, CloudFront-Signature or CloudFront-Key-Pair-Id in my cookies. And the functionality that this is supposed to enable isn't working. These two show me the cookies aren't coming over. What is the situation?
As per my understanding I am doing everything correctly

Related

cloud front signed cookies not being set by django set_cookie?

first Here is my code setting up cookies in my response:
cookies = dist.create_signed_cookies(resource,expire_minutes=expire_minutes)
taco = HttpResponse(json.dumps(payload))
taco.set_cookie('CloudFront-Policy', cookies[1]['CloudFront-Policy'], domain=cookies[0], httponly=False)
taco.set_cookie('CloudFront-Signature', cookies[1]['CloudFront-Signature'], domain=cookies[0],
httponly=False)
taco.set_cookie('CloudFront-Key-Pair-Id', cookies[1]['CloudFront-Key-Pair-Id'], domain=cookies[0],
httponly=False)
print('here comes the tacos')
print(taco)
return taco
now when we go to the chrome inspector I do not see CloudFront-Policy, CloudFront-Signature
am I correct that these cookies are not being sent?
See no cloudfront url

Response cookies using for next requests

As I see from the answer for this question: Karate will automatically send any cookies returned by the server in the next request.
But when I send the request I see two sets of cookies in Set-Cookie of response: one is auto-created and another is real, that returned from the server.
When I printed responseCookies, I saw there only automatic cookies
and for the next request new cookies are generated and sent.
For my test I need to use cookies returned after the first request because it is a call to login service.
Feature: Using cookies in next request
Background:
Given url baseUrl
And path LOGOUT_SERVICE_ENDPOINT
And configure headers = read('classpath:headers.js')
And def filename = 'classpath:resources/users/' + brand.toLowerCase() + '/user.json'
And json user = read(filename)
Scenario: Login
When def login = callonce read('classpath:features/login_service/login.feature') user
* print login.responseCookies
And request { arg1: '#(brand)'}
And method post
Then status 200
What is wrong in my feature or it is Karate issue?
two sets of cookies in Set-Cookie of response:
Maybe that is a bug in the server ?
Also try using "shared scope", because cookies also will be part of the "global" variables etc.
* callonce read('classpath:features/login_service/login.feature') user
* request { arg1: '#(brand)'}
If you are still stuck, please follow this process: https://github.com/intuit/karate/wiki/How-to-Submit-an-Issue

Django: why CSRF_COOKIE in request.META

I used requests to send request.
import requests
def print(req):
print('{}\n{}\n{}\n\n{}'.format(
'-----------START-----------',
req.method + ' ' + req.url,
'\n'.join('{}: {}'.format(k, v) for k, v in req.headers.items()),
req.body,
))
print "----------END------------"
try:
req = requests.Request('GET',
'https://myip/myproject/upload/token',
headers={'Authorization': 'Token 401f7ac837a',
})
prepared = req.prepare()
print(prepared)
except Exception as e:
print "Exception:", e
Output:
-----------START-----------
GET https://myip/myproject/upload/token
Authorization: Token 401f7ac837a
None
----------END------------
But after I printed the request.META, there is
META:{u'CSRF_COOKIE': u'YGzoMaNEQJz1Kg8yXAwjJt6yNuT9L'
What set the CSRF_COOKIE?
Any comments welcomed. Thanks
UPDATE
(1)
From the doc, it said This cookie is set by CsrfViewMiddleware, which means the CSRF cookie was set in back-end and set to front-end in the response (CSRF cookie: server -> browser). Why it also said For all incoming requests that are not using HTTP GET, HEAD, OPTIONS or TRACE, a CSRF cookie must be present? And why it appears in my request.META? (CSRF cookie: browser -> server ???)
(2)
It said **A hidden form field with the name ‘csrfmiddlewaretoken’ present in all outgoing POST forms. The value of this field is the value of the CSRF cookie.
This part is done by the template tag.
**
When and How the template tag do it?
This is a standard cookie Django applications spin up for each new user to prevent Cross Site Forgery.
A CSRF cookie that is set to a random value (a session independent
nonce, as it is called), which other sites will not have access to.
This cookie is set by CsrfViewMiddleware. It is meant to be permanent,
but since there is no way to set a cookie that never expires, it is
sent with every response that has called
django.middleware.csrf.get_token() (the function used internally to
retrieve the CSRF token).
For security reasons, the value of the CSRF cookie is changed each
time a user logs in.
for more reading
https://docs.djangoproject.com/en/1.9/ref/csrf/#how-it-works

Flash + pyAMF + Django session cookie security

First off, if there is a true, official way of having flash/flex's NetConnections usurp the session/cookie state of the surrounding web page, so that if the user has already logged in, they don't need to provide credentials again just to set up an AMF connection, please stop me now and post the official answer.
Barring that, I'm assuming there is not, as I have searched and it seems to not exist. I've concocted a means of doing this, but want some feedback as to whether it is secure.
Accessing a wrapper-page for a flash object will always go to secure https due to django middleware
When the page view is loaded in Django, it creates a "session alias" object with a unique key that points to the current session in play (in which someone ostensibly logged in)
That session alias model is saved, and that key is placed into a cookie whose key is another random string, call it randomcookie
That randomcookie key name is passed as a context variable and written into the html as a flashvar to the swf
The swf is also loaded only via https
The flash application uses ExternalInterface to call java to grab the value at that randomcookie location, and also deletes the cookie
It then creates a NetConnection to a secure server https location, passing that randomcookie as an argument (data, not in the url) to a login-using-cookie rpc
At the gateway side, pyamf looks up the session alias and gets the session it points to, and logs in the user based on that (and deletes the alias, so it can't be reused)
(And the gateway request could also set the session cookie and session.session_key to the known session ID, but I could let it make a whole new session key... I'm assuming that doing so should affect the response properly so that it contains the correct session key)
At this point, the returned cookie values on the flash side should stick to the NetConnection so that further calls are authenticated (if a connection is authenticated using username and password the normal way, this definitely works, so I think this is a safe bet, testing will soon prove or disprove this)
So, is this unsafe, or will this work properly? As far as I know, since the html page is guaranteed to be over ssl, the key and cookie data should be encrypted and not steal-able. Then, the info therein should be safe to use one-time as basically a temporary password, sent again over ssl because the gateway is also https. After that, it's using the normal pyAMF system over https and not doing anything out of the ordinary.
No responses on this so far, so the best I can do is confirm that it does in fact physically work. For details on how to set up Flex Builder to write html-wrappers that communicate with Django pages templates, see my other post. The above was accomplished using a combination of the aforementioned, plus:
Made a SessionAlias model:
class SessionAlias(models.Model):
alias = models.CharField( max_length=40, primary_key=True )
session = models.ForeignKey( Session )
created = models.DateTimeField( auto_now_add=True )
Flex points to a Django page that loads via a view containing:
s = SessionAlias()
s.alias = SessionStore().session_key // generates new 40-char random
s.session = Session.objects.get( session_key=request.session.session_key )
s.save();
randomcookie = SessionStore().session_key // generates new 40-char random
kwargs['extra_context']['randomcookie'] = randomcookie
response = direct_to_template( request, **kwargs )
response.set_cookie( randomcookie, value=alias )
In the flex html-wrapper, where randomcookie is the location to look for the alias:
<param name="flashVars" value="randomcookie={{randomcookie}}" />
In applicationComplete, where we get randomcookie and find the alias, and log on using that:
var randomcookie:String = this.parameters["randomcookie"];
// randomcookie is something like "abc123"
var js:String = "function get_cookie(){return document.cookie;}";
var cookies:String = ExternalInterface.call(js).toString();
// cookies looks like "abc123=def456; sessionid=ghi789; ..."
var alias:String = // strip out the "def456"
mynetconnection.call( "loginByAlias", alias, successFunc, failureFunc );
Which in turn access this pyamf gateway rpc:
from django.contrib.auth import SESSION_KEY, load_backend
from django.contrib.auth.models import User
from django.contrib import auth
from django.conf import settings
def loginByAlias( request, alias ):
a = SessionAlias.objects.get( alias=alias )
session_engine = __import__( settings.SESSION_ENGINE, {}, {}, [''] )
session_wrapper = session_engine.SessionStore( a.session.session_key )
user_id = session_wrapper.get( SESSION_KEY )
user = User.objects.get( id=user_id )
user.backend='django.contrib.auth.backends.ModelBackend'
auth.login( request, user )
a.delete()
return whateverToFlash
And at that point, on the flash/flex side, that particular mynetconnection retains the session cookie state that can make future calls such that, inside the gateway, request.user is the properly-authenticated user that logged onto the webpage in the first place.
Note again that the run/debug settings for flex must use https, as well as the gateway settings for NetConnection. And when releasing this, I have to make sure that authenticated users stay on https.
Any further info from people would be appreciated, especially if there's real feedback on the security aspects of this...
IE doesn't give access to cookies in local development but if you publish the SWF and put on a domain, it should pickup the session just like ever other browser. Use Firefox 3.6 to build your flex apps locally.
Tested in IE8, Firefox using a pyamf gateway on Flex 3 with NetConnection. The gateway function was decorated with #login_required

Cross-Domain Cookies

I have two webapps WebApp1 and WebApp2 in two different domains.
I am setting a cookie in WebApp1 in the HttpResponse.
How to read the same cookie from HttpRequest in WebApp2?
I know it sounds weird because cookies are specific to a given domain, and we can't access them from different domains; I've however heard of CROSS-DOMAIN cookies which can be shared across multiple webapps. How to implement this requirement using CROSS-DOMAIN cookies?
Note: I am trying this with J2EE webapps
Yes, it is absolutely possible to get the cookie from domain1.example by domain2.example. I had the same problem for a social plugin of my social network, and after a day of research I found the solution.
First, on the server side you need to have the following headers:
header("Access-Control-Allow-Origin: http://origin.domain:port");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET, POST");
header("Access-Control-Allow-Headers: Content-Type, *");
Within the PHP-file you can use $_COOKIE[name]
Second, on the client side:
Within your AJAX request you need to include 2 parameters
crossDomain: true
xhrFields: { withCredentials: true }
Example:
type: "get",
url: link,
crossDomain: true,
dataType: 'json',
xhrFields: {
withCredentials: true
}
As other people say, you cannot share cookies, but you could do something like this:
centralize all cookies in a single domain, let's say cookiemaker.example
when the user makes a request to example.com you redirect him to cookiemaker.example
cookiemaker.example redirects him back to example.com with the information you need
Of course, it's not completely secure, and you have to create some kind of internal protocol between your apps to do that.
Lastly, it would be very annoying for the user if you do something like that in every request, but not if it's just the first.
But I think there is no other way.
As far as I know, cookies are limited by the "same origin" policy. However, with CORS you can receive and use the "Server B" cookies to establish a persistent session from "Server A" on "Server B".
Although, this requires some headers on "Server B":
Access-Control-Allow-Origin: http://server-a.example.com
Access-Control-Allow-Credentials: true
And you will need to send the flag "withCredentials" on all the "Server A" requests (ex: xhr.withCredentials = true;)
You can read about it here:
http://www.html5rocks.com/en/tutorials/cors/
https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS
There's no such thing as cross domain cookies. You could share a cookie between foo.example.com and bar.example.com but never between example.com and example2.com and that's for security reasons.
The smartest solution is to follow facebook's path on this. How does facebook know who you are when you visit any domain? It's actually very simple:
The Like button actually allows Facebook to track all visitors of the external site, no matter if they click it or not. Facebook can do that because they use an iframe to display the button. An iframe is something like an embedded browser window within a page. The difference between using an iframe and a simple image for the button is that the iframe contains a complete web page – from Facebook. There is not much going on on this page, except for the button and the information about how many people have liked the current page.
So when you see a like button on cnn.com, you are actually visiting a Facebook page at the same time. That allows Facebook to read a cookie on your computer, which it has created the last time you’ve logged in to Facebook.
A fundamental security rule in every browser is that only the website that has created a cookie can read it later on. And that is the advantage of the iframe: it allows Facebook to read your Facebook-cookie even when you are visiting a different website. That’s how they recognize you on cnn.com and display your friends there.
Source:
http://dorianroy.com/blog/2010/04/how-facebooks-like-button-works/
https://stackoverflow.com/a/8256920/715483
Cross-domain cookies are not allowed (i.e. site A cannot set a cookie on site B).
But once a cookie is set by site A, you can send that cookie even in requests from site B to site A (i.e. cross-domain requests):
XMLHttpRequest from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request. The third-party cookies obtained by setting withCredentials to true will still honor same-origin policy and hence can not be accessed by the requesting script through document.cookie or from response headers.
Make sure to do these things:
When setting the cookie in a response
The Set-Cookie response header includes SameSite=None if the requests are cross-site (note a request from www.example.dev to static.example.dev is actually a same-site request, and can use SameSite=Strict)
The Set-Cookie response header should include the Secure attribute if served over HTTPS; as seen here and here
When sending/receiving the cookie:
The request is made with withCredentials: true, as mentioned in other answers here and here, including the original request whose response sets the cookie set in the first place
For the fetch API, this attribute is credentials: 'include', vs withCredentials: true
For jQuery's ajax method, note you may need to supply argument crossDomain: true
The server response includes cross-origin headers like Access-Control-Allow-Origin, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, and Access-Control-Allow-Methods
As #nabrown points out: "Note that the "Access-Control-Allow-Origin" cannot be the wildcard (*) value if you use the withCredentials: true" (see #nabrown's comment which explains one workaround for this.
In general:
Your browser hasn't disabled 3rd-party cookies. (* see below)
Things that you don't need (just use the above):
domain attribute in the Set-Cookie; you can choose a root domain (i.e. a.example.com can set a cookie with a domain value of example.com, but it's not necessary; the cookie will still be sent to a.example.com, even if sent from b.other-site.example
For the cookie to be visible in Chrome Dev Tools, "Application" tab; if the value of cookie HttpOnly attribute is true, Chrome won't show you the cookie value in the Application tab (it should show the cookie value when set in the initial request, and sent in subsequent responses where withCredentials: true)
Notice the difference between "path" and "site" for Cookie purposes. "path" is not security-related; "site" is security-related:
path
Servers can set a Path attribute in the Set-Cookie, but it doesn't seem security related:
Note that path was intended for performance, not security. Web pages having the same origin still can access cookie via document.cookie even though the paths are mismatched.
site
The SameSite attribute, according to example.dev article, can restrict or allow cross-site cookies; but what is a "site"?
It's helpful to understand exactly what 'site' means here. The site is the combination of the domain suffix and the part of the domain just before it. For example, the www.example.dev domain is part of the example.dev site...
This means a request to static.example.dev from www.example.dev, is a sameSite request (the only difference in the URLs is in the subdomains).
The public suffix list defines this, so
it's not just top-level domains like .com but also includes services
like github.io
This means a request to your-project.github.io from my-project.github.io, is a a cross-site request (these URLs are at different domains, because github.io is the domain suffix; the domains your-project vs my-project are different; hence different sites)
This means what's to the left of the public suffix; is the subdomain (but the subdomain is a part of the host; see the BONUS reply in this answer)
www is the subdomain in www.example.dev; same site as static.example.dev
your-project is the domain in your-project.github.io; separate site as my-project.github.io
In this URL https://www.example.com:8888/examples/index.html, remember these parts:
the "protocol": https://
the "scheme": https
the "port": 8888
the "domain name" aka location.hostname: www.example.com
the "domain suffix" aka "top-level domain" (TLD): com
the "domain": example
the "subdomain": www (the subdomain could be single-level (like www) or multi-level (like foo.bar in foo.bar.example.com)
the "site" (as in "cross-site" if another URL had a different "site" value): example.com
"site" = "domain" + "domain suffix" = example.com
the "path": /examples/index.html
Useful links:
Anatomy of a URL
Same-Origin cookie policy and URL anatomy
SameSite cookies explained
Secure cross-domain cookies for HTTP | Journal of Internet Services and Applications | Full Text
draft-ietf-httpbis-rfc6265bis-03
Web Security 1: Same-Origin and Cookie Policy
Set-Cookie - HTTP | MDN
(Be careful; I was testing my feature in Chrome Incognito tab; according to my chrome://settings/cookies; my settings were "Block third party cookies in Incognito", so I can't test Cross-site cookies in Incognito.)
You cannot share cookies across domains. You can however allow all subdomains to have access. To allow all subdomains of example.com to have access, set the domain to .example.com.
It's not possible giving other.example access to example.com's cookies though.
Do what Google is doing. Create a PHP file that sets the cookie on all 3 domains. Then on the domain where the theme is going to set, create a HTML file that would load the PHP file that sets cookie on the other 2 domains. Example:
<html>
<head></head>
<body>
<p>Please wait.....</p>
<img src="http://domain2.example/setcookie.php?theme=whateveryourthemehere" />
<img src="http://domain3.example/setcookie.php?theme=whateveryourthemehere" />
</body>
</html>
Then add an onload callback on body tag. The document will only load when the images completely load that is when cookies are set on the other 2 domains. Onload Callback:
<head>
<script>
function loadComplete(){
window.location="http://domain1.example";//URL of domain1
}
</script>
</head>
<body onload="loadComplete()">
setcookie.php
We set the cookies on the other domains using a PHP file like this:
<?php
if(isset($_GET['theme'])){
setcookie("theme", $_GET['theme'], time()+3600);
}
?>
Now cookies are set on the three domains.
You can attempt to push the cookie val to another domain using an image tag.
Your mileage may vary when trying to do this because some browsers require you to have a proper P3P Policy on the WebApp2 domain or the browser will reject the cookie.
If you look at plus.google.com p3p policy you will see that their policy is:
CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."
that is the policy they use for their +1 buttons to these cross domain requests.
Another warning is that if you are on https make sure that the image tag is pointing to an https address also otherwise the cookies will not set.
There's a decent overview of how Facebook does it here on nfriedly.com
There's also Browser Fingerprinting, which is not the same as a cookie, but serves a like purpose in that it helps you identify a user with a fair degree of certainty. There's a post here on Stack Overflow that references upon one method of fingerprinting
I've created an NPM module, which allows you to share locally-stored data across domains:
https://www.npmjs.com/package/cookie-toss
By using an iframe hosted on Domain A, you can store all of your user data on Domain A, and reference that data by posting requests to the Domain A iframe.
Thus, Domains B, C, etc. can inject the iframe and post requests to it to store and access the desired data. Domain A becomes the hub for all shared data.
With a domain whitelist inside of Domain A, you can ensure only your dependent sites can access the data on Domain A.
The trick is to have the code inside of the iframe on Domain A which is able to recognize which data is being requested. The README in the above NPM module goes more in depth into the procedure.
Hope this helps!
Since it is difficult to do 3rd party cookies and also some browsers won't allow that.
You can try storing them in HTML5 local storage and then sending them with every request from your front end app.
One can use invisible iframes to get the cookies. Let's say there are two domains, a.example and b.example. For the index.html of domain a.example one can add (notice height=0 width=0):
<iframe height="0" id="iframe" src="http://b.example" width="0"></iframe>
That way your website will get b.example cookies assuming that http://b.example sets the cookies.
The next thing would be manipulating the site inside the iframe through JavaScript. The operations inside iframe may become a challenge if one doesn't own the second domain. But in case of having access to both domains referring the right web page at the src of iframe should give the cookies one would like to get.
Along with #Ludovic(approved answer) answers we need to check one more option when getting set-cookies header,
set-cookie: SESSIONID=60B2E91C53B976B444144063; Path=/dev/api/abc; HttpOnly
Check for Path attribute value also. This should be the same as your API starting context path like below
https://www.example.com/dev/api/abc/v1/users/123
or use below value when not sure about context path
Path=/;
function GetOrder(status, filter) {
var isValid = true; //isValidGuid(customerId);
if (isValid) {
var refundhtmlstr = '';
//varsURL = ApiPath + '/api/Orders/Customer/' + customerId + '?status=' + status + '&filter=' + filter;
varsURL = ApiPath + '/api/Orders/Customer?status=' + status + '&filter=' + filter;
$.ajax({
type: "GET",
//url: ApiPath + '/api/Orders/Customer/' + customerId + '?status=' + status + '&filter=' + filter,
url: ApiPath + '/api/Orders/Customer?status=' + status + '&filter=' + filter,
dataType: "json",
crossDomain: true,
xhrFields: {
withCredentials: true
},
success: function (data) {
var htmlStr = '';
if (data == null || data.Count === 0) {
htmlStr = '<div class="card"><div class="card-header">Bu kriterlere uygun sipariş bulunamadı.</div></div>';
}
else {
$('#ReturnPolicyBtnUrl').attr('href', data.ReturnPolicyBtnUrl);
var groupedData = data.OrderDto.sort(function (x, y) {
return new Date(y.OrderDate) - new Date(x.OrderDate);
});
groupedData = _.groupBy(data.OrderDto, function (d) { return toMonthStr(d.OrderDate) });
localStorage['orderData'] = JSON.stringify(data.OrderDto);
$.each(groupedData, function (key, val) {
var sortedData = groupedData[key].sort(function (x, y) {
return new Date(y.OrderDate) - new Date(x.OrderDate);
});
htmlStr += '<div class="card-header">' + key + '</div>';
$.each(sortedData, function (keyitem, valitem) {
//Date Convertions
if (valitem.StatusDesc != null) {
valitem.StatusDesc = valitem.StatusDesc;
}
var date = valitem.OrderDate;
date = date.substring(0, 10).split('-');
date = date[2] + '.' + date[1] + '.' + date[0];
htmlStr += '<div class="col-lg-12 col-md-12 col-xs-12 col-sm-12 card-item clearfix ">' +
//'<div class="card-item-head"><span class="order-head">Sipariş No: <a href="ViewOrderDetails.html?CustomerId=' + customerId + '&OrderNo=' + valitem.OrderNumber + '" >' + valitem.OrderNumber + '</a></span><span class="order-date">' + date + '</span></div>' +
'<div class="card-item-head"><span class="order-head">Sipariş No: <a href="ViewOrderDetails.html?OrderNo=' + valitem.OrderNumber + '" >' + valitem.OrderNumber + '</a></span><span class="order-date">' + date + '</span></div>' +
'<div class="card-item-head-desc">' + valitem.StatusDesc + '</div>' +
'<div class="card-item-body">' +
'<div class="slider responsive">';
var i = 0;
$.each(valitem.ItemList, function (keylineitem, vallineitem) {
var imageUrl = vallineitem.ProductImageUrl.replace('{size}', 200);
htmlStr += '<div><img src="' + imageUrl + '" alt="' + vallineitem.ProductName + '"><span class="img-desc">' + ProductNameStr(vallineitem.ProductName) + '</span></div>';
i++;
});
htmlStr += '</div>' +
'</div>' +
'</div>';
});
});
$.each(data.OrderDto, function (key, value) {
if (value.IsSAPMigrationflag === true) {
refundhtmlstr = '<div class="notify-reason"><span class="note"><B>Notification : </B> Geçmiş siparişleriniz yükleniyor. Lütfen kısa bir süre sonra tekrar kontrol ediniz. Teşekkürler. </span></div>';
}
});
}
$('#orders').html(htmlStr);
$("#notification").html(refundhtmlstr);
ApplySlide();
},
error: function () {
console.log("System Failure");
}
});
}
}
Web.config
Include UI origin and set Allow Credentials to true
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://burada.com" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
Three main kinds of browser-based storage:
session storage
local storage
cookie storage
Secure cookies - are used by encrypted websites to offer protection from any possible threats from a hacker.
access cookie - document.cookie. This means that this cookie is exposed and can be exploited through cross-site scripting. The saved cookie values can be seen through the browser console.
As a precaution, you should always try to make your cookies inaccessible on the client-side using JavaScript.
HTTPonly - ensures that a cookie is not accessible using the JavaScript code. This is the most crucial form of protection against cross-scripting attacks.
A secure attribute - ensures that the browser will reject cookies unless the connection happens over HTTPS.
sameSite attribute improves cookie security and avoids privacy leaks.
sameSite=Lax - It is set to Lax (sameSite = Lax) meaning a cookie is only set when the domain in the URL of the browser matches the domain of the cookie, thus eliminating third party’s domains. This will restrict cross-site sharing even between different domains that the same publisher owns. we need to include SameSite=None to avoid the new default of Lax:
Note: There is a draft spec that requires that the Secure attribute be set to true when the SameSite attribute has been set to 'none'. Some web browsers or other clients may be adopting this specification.
Using includes as { withCredentials: true } must include all the cookies with the request from the front end.
const data = { email: 'youremailaddress#gmail.com' , password: '1234' };
const response = await axios.post('www.yourapi.com/login', data , { withCredentials: true });
Cookie should only be accepted over a secure HTTPS connection. In order to get this to work, we must move the web application to HTTPS.
In express.js
res.cookie('token', token, {
maxAge: 1000 * 60 * 60 * 24, // would expire after (for 15 minutes 1000 * 60 * 15 ) 15 minutes
httpOnly: true, // The cookie only accessible by the web server
sameSite: 'none',
secure: true, // Marks the cookie to be used with HTTPS only.
});
Reference 1, Reference 2
Read Cookie in Web Api
var cookie = actionContext.Request.Headers.GetCookies("newhbsslv1");
Logger.Log("Cookie " + cookie, LoggerLevel.Info);
Logger.Log("Cookie count " + cookie.Count, LoggerLevel.Info);
if (cookie != null && cookie.Count > 0)
{
Logger.Log("Befor For " , LoggerLevel.Info);
foreach (var perCookie in cookie[0].Cookies)
{
Logger.Log("perCookie " + perCookie, LoggerLevel.Info);
if (perCookie.Name == "newhbsslv1")
{
strToken = perCookie.Value;
}
}
}