Using cookie with HTTPS - cookies

I'm working on https and I had a problem about a cookie
If I deploy in a http, cookie is stored and read normally. But when deploy in https, cookie is not stored and read also even though I set a "secure=true" in a jquery cookie configuration like this
$.cookie("mycookie", "hello", { expires: 365, path: "/", secure: true });
and...
$.cookie("mycookie", "hello", { expires: 365, path: "/" }); is not work as well
Do you have some idea to get the cookie works with https protocol?

Related

Unable to pass _oauth2_proxy_{0,1,2} cookies in cors calls to istio

I have a service blocked under oauth2_proxy which requires login , however i am unable to to pass theses oauth2_proxy cookies when making cors calls.
I have tried
return $.ajax({
url: url,
...
xhrFields: {
withCredentials: true
},
crossDomain: true,
...
});
}
and on the server side , I have ensured that all origins are whitelisted with a whitelist.
Is there a way to pass `oauth2_proxy{0,1,2}` cookies for cors calls?
Here is my configuration
- - oauth2-proxy
- --use-oidc-implicit-flow=false
- --ssl-upstream-insecure-skip-verify=true
- --oidc-client-id-path=/vault-secrets/service-client-id
- --oidc-client-secret-path=/vault-secrets/service-client-secret
- --oidc-cookie-secret-path=/vault-secrets/cookie-secret
- --pass-authorization-header=true
- --pass-access-token=true
- --set-authorization-header=true
- --set-xauthrequest=true
- --reverse-proxy=true

returning response with set-cookie header in AWS Cloudfront origin request

In my CloudFront origin request lambda#edge function I want to return a response which will set a cookie value in the browser and redirects to other page. I do it by the following return statement:
return {
status: '302',
statusDescription: 'Found',
headers: {
location: [
{ key: 'Location', value: 'my.website.com' },
],
'set-cookie': [
{ key: 'Set-Cookie', value: 'key=value; Max-Age=600' },
]
}
};
Unfortunately CloudFront seems to remove/ignore this set-cookie header and the browser receives a response without it. What's interesting, the exact same code works when placed in the CloudFront viewer-request function. Is there a way to make origin-request lambda to keep the set-cookie header in the response?
The solution turn out to be a cache policy with Cookies - include specified cookies option turned on with proper whitelisted cookie name. The behaviour in the question is caused (as documentation states) by:
Don’t forward cookies to your origin – CloudFront doesn’t cache your objects based on cookie sent by the viewer. In addition, CloudFront removes cookies before forwarding requests to your origin, and removes Set-Cookie headers from responses before returning responses to your viewers.
To prevent caching by whitelisted cookie name add the following header to the response: Cache-Control: no-cache="Set-Cookie".

SameSite: lax cookie doesn't work with Safari

I have a website www.hello.app (example url) and a server www.server.hello.app. The server sends http-only cookie for authentification.
I've added the attribute sameSite: "lax" when creating the cookie. sameSite: "none" and sameSite: "lax" don't work with Safari. It doesn't store any cookie, so the user can't perform any request on the server.
return res
.status(200)
.cookie("hello", token, {
expires: new Date(Date.now() + msPerDay * 14),
httpOnly: true,
secure: true,
sameSite: "lax",
})
.json({ user });
I've heard it's a bug, but I can't believe such a widely used browser hamper authenticated requests like this!
Is there a way to fix this?

Vue PWA login works in dev but returns 401 in production

I have a Vue.js PWA with a Django Rest Framework backend which works correctly locally on my laptop (using a browser). When I deploy it to production it continues to work correctly when I log in using a browser, however it fails to login when opened as a PWA (ie: on a phone or a PWA saved in a browser).
Here's my login code:
axios
.post("/api/get-token/", user)
.then(res => {
localStorage.setItem('user-token', res.data.token);
axios.defaults.headers.common['Authorization'] = res.data.token;
commit(AUTH_SUCCESS, res.data);
resolve(res);
})
.catch(err => {
commit(AUTH_ERROR, err);
reject(err);
});
As mentioned, everything works locally and in production when logging in via a browser. The problem comes when trying to log in using the PWA.
When trying to login to the PWA, I get the following:
POST https://www.example.com/api/get-token/ 401 (Unauthorized)
Doing a console log of the error received from the server I get:
{
detail: "Invalid token header. No credentials provided."
__proto__: Object
status: 401
statusText: "Unauthorized"
headers: {allow: "POST, OPTIONS", connection: "keep-alive", content-length: "59", content-type: "application/json", date: "Thu, 06 Feb 2020 15:00:11 GMT", …}
config:
url: "/api/get-token/"
method: "post"
data: "{"username":"test#example.com","password":"password"}"
headers:
Accept: "application/json, text/plain, */*"
Authorization: "Token "
Content-Type: "application/json;charset=utf-8"
__proto__: Object
transformRequest: [ƒ]
transformResponse: [ƒ]
timeout: 0
adapter: ƒ (t)
xsrfCookieName: "csrftoken"
xsrfHeaderName: "X-CSRFToken"
maxContentLength: -1
validateStatus: ƒ (t)
}
In production, the following works:
Log into the site using a browser on my laptop or on a phone.
Then open the PWA. This works correctly and I can continue using the PWA.
The only issue comes when trying to log in using the PWA.
Can you log in on a phone locally? I had this problem too once, the problem was that the frontend and backend were not running on the same host. This solved my problem:
devServer: {
proxy: {
'/api': {
target: 'http://localhost:5000'
}
}
}
I eventually figured out the issue. For some reason the following was being POSTed in the header: Authorization: "Token ".
This is really strange because when logging in using the /api/get-token/ there is no token required since this is the login route. Also, it works perfectly from a browser. The only issue is when trying from a PWA.
Anyway, changing the header to explicitly have no value for Authorization fixed the issue as follows: Authorization: ""

React + Django Axios Issues

I have a react application linked to a Django backend on two separate servers. I am using DRF for django and I allowed cors using django-cors-headers. For some reason when I curl POST the backend, I am able to get the request out. However when I use axios POST the backend, I get and error. The status of the POST request from axios is failed. The request and takes more than 10 seconds to complete. My code was working locally (both react and django codes), but when I deployed to AWS ec2 ubuntu, the axios requests stopped working.
Console error logs
OPTIONS http://10.0.3.98:8000/token-auth/ net::ERR_CONNECTION_TIMED_OUT
{
"config": {
"transformRequest": {},
"transformResponse": {},
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json;charset=UTF-8",
"Access-Control-Allow-Origin": "*"
},
"method": "post",
"url": "http://10.0.3.98:8000/token-auth/",
"data": "{\"username\":\"testaccount\",\"password\":\"testpassword\"}"
},
"request": {}
}
Here is my request code
axios.post('http://10.0.3.98:8000/token-auth/',
JSON.stringify(data),
{
mode: 'no-cors',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin' : '*'
},
},
).then( res => (
console.log(JSON.stringify(res)),
)
).catch( err => (
console.log(JSON.stringify(err))
)
);
my curl code that worked
curl -d '{"username":"testaccount", "password":"testpassword"}' -H "Content-Type: application/json" -X POST http://10.0.3.98:8000/token-auth/
UPDATE 1
on firefox i am getting the warning
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at http://10.0.3.98:8000/token-auth/. (Reason:
CORS request did not succeed).[Learn More]
UPDATE 2
Perhaps it has something to do with my AWS VPC and subnets? My django server is in a private subnet while my react app is in a public subnet.
UPDATE 3 - my idea of what the problem is
I think the reason why my requests from axios aren't working is because the requests i'm making is setting the origin of the request header to http://18.207.204.70:3000 - the public/external ip address - instead of the private/internal ip address which is http://10.0.2.219:3000 - i search online that the origin is a forbidden field so it can't be changed. How can i set the origin then? Do I have to use a proxy - how can I do that.
try this http request instead of axios, it's called superagent (https://www.npmjs.com/package/superagent) , just install it to your react app via npm,
npm i superagent
and use this instead of axios.
import request from 'superagent'
const payload ={
"1": this.state.number,
"2": this.state.message
}
request.post('LINK HERE')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(payload)
.end(function(err, res){
if (res.text==='success'){
this.setState({
msgAlert: 'Message Sent!',
})
}
else{
console.log('message failed/error')
}
});
The issue here is that the request is being made on the client browser. You need to either use a reverse proxy or request directly to the api server. You cannot do a local ssh forwarding either.