Use same ss-id cookie across all subdomains - ServiceStack - cookies

In my Auth API set the ss-id cookie domain to be used for all subdomains like so in my AppHost.Configure method:
Config = new HostConfig
{
RestrictAllCookiesToDomain = ".mywebsite.com"
};
My browser will include this cookie in every request to every every subdomain API of mine, for example: user.mywebsite.com.
Unfortunately, my APIs are responding with SET COOKIE responses, intermittently!
So sometimes I get what I do not want with my ss-id Cookie:
And sometimes, logging in and out, clearing my cookies for mywebsite.com I can get what I want and my APIs are sharing the same cookie:
I have attempted to add:
Config = new HostConfig
{
RestrictAllCookiesToDomain = ".mywebsite.com"
};
To other APIs' AppHost.Configure but this does not seem to remedy the situation, nor does it seem necessary because the ss-id cookie set by my auth API successful login response is for all subdomains (.mywebsite.com)
I am suspecting that Ajax requests are being sent to APIs without the ss-id cookie have been set yet, a timing issue across multiple Ajax requests and the login process.
Is my logic correct? Since the ss-id SET COOKIE domain in the response header for the initial response is .mywebsite.com after login that none of my other APIs will respond with a new SET COOKIE for ss-id?

You’re not going to know what’s happening unless you view the raw HTTP Headers to see what’s actually happening.
It’s possible there’s a race condition with multiple Ajax requests which we’re initially sent without ss-id cookies in which case they can have different ss-id cookies returned in which case the last Set-Cookie instruction will win and be used going forward provided they all use the same / path.

Related

JMeter 5.4.1 Cookie Manager - User-Defined Cookie not added to request's cookies

Firstly, I did add the line CookieManager.check.cookies=false to jmeter.properties.
What I'm Trying to Do
I want to add a cookie to a request's existing cookies.
For example, I see the request has [edited]:
Cookie Data:
c1=sfasfsfsfsfs; c2=erqwerqwrr; c3=poiuopiupoi
Expected Results
I would like it to have:
Cookie Data:
c1=sfasfsfsfsfs; c2=erqwerqwrr; c3=poiuopiupoi; partner=favicon.ico
Here is what I tried:
BASE_URL_2 is a variable defined in the form qa.company.com.
Actual Results
Whatever I have tried so far has not made any change in the cookies.
What else shall I try?
Underlying Motivation
Recorded a Web session and played it back.
Added a RegEx Extractor to pull out a token and then added it to subsequent requests. That helped.
However, certain requests failed with an custom application exception Security violation, please refresh.
Probably session login state is not being passed, so the website thinks the call is "stale".
I've seen this on the GUI when the session expires and you try to click a button on the site.
On comparing the cookies seem in JMeter with what I saw in the Chrome Debugger, it was clear that there were more cookies in the running application than what I had in JMeter.
Are you sure you're using HTTPS protocol because if you have secure flag and using HTTP protocol - the cookie will not be sent.
Also remove = from partner= otherwise you will end up with partner==favicon.ico
Demo:
More information:
Using HTTP cookies
HTTP Cookie Manager Advanced Usage - A Guide

Set-Cookie from a server to an XHR client in a different domain, setting the domain to the client's domain, should it work?

tl;dr, an XHR client in domain A is sending a request to a server in domain B, server responds with a Set-Cookie with Domain=A (the client's domain, the XHR's Origin), all CORS headers set correctly, should it work?
It's well known that one can't set a cookie to another domain. ( How to set a cookie for another domain
However given the following scenario:
Actors:
Client in domain A, a web based client
Server in domain B, setup with CORS headers permitting A as origin, including Access-Control-Allow-Credentials set to true
Communication flow 1 (baseline):
Client is issuing a simple GET request to the Server
Server responds with a cookie, and sets the Domain property to be of the server (Domain=B)
Client is sending another HXR request and has withCredentials=true
The cookie is sent back to the server without any issues
Note: the cookie sent in step #1 is not showing in document.cookies, even if it was not set as httpOnly (since it doesn't
belong to the client's domain). Also attempts to get it from the xhr
via looking at the "Set-Cookie" header, you'll be blocked, by design:
https://fetch.spec.whatwg.org/#forbidden-response-header-name it will
even won't show in Chrome dev tools under the network tab! but it will
still be sent)
Communication flow 2 (my question):
Client is issuing a simple GET request to the Server
Server responds with a cookie, but sets the Domain property to be of the client (Domain=A)
Client is sending an HXR request and has withCredentials=true
The cookie is not sent back and doesn't seem to be stored anywhere
Why am I a bit surprised? Since the XHR origin is A and it requests something that sets the cookie to domain A (if I look in Postman I clearly see the Set-Cookie header being sent with Domain being the same as the request's Origin), and I have the most permissive CORS setting for that, what's the reasoning behind not letting me do it? (I was expecting it to fail, but still made me wonder)
Questions
Where is the best place in the spec/RFC that it clarifies that this won't work also for XHR where the cookie Domain equals the Origin
What is the attack vector in scenario 2 if theoretically the browser did allow the server to store the cookie if and only if the Origin is the same as the cookie Domain and the CORS origin allows that Origin.
Is there another way to make it work? Maybe it works but my POC was setup incorrectly?
Appendix: Reasoning
I'm looking for a way to have a cross origin CSRF using something like the Cookie to header token method, but due to the cross origin issue, it seems that it's impossible. The only workaround I thought of is sending the CSRF token as a header from the server, then the client can just save it as a cookie it can access later, is there any other way to do it? Is this considered secure?
A resource can only set cookies for its host's registrable domain. If Facebook were to use Google Fonts, and Google could use that to override Facebook cookies, that'd be pretty disastrous.
As for where this is defined, step 5 and 6 of https://www.rfc-editor.org/rfc/rfc6265#section-5.3 handle this. (Fetch largely defers to this RFC when it comes to interpreting the Set-Cookie header on responses.)

How to work with sessions in Vue and Flask?

You know, web applications needs sessions or cookies to authentication. I trying to build web application with Vue.JS and Flask microframework for example ERP or CRM.
I'm confused. How can I work with sessions? Let's think we have a code like this in the Flask:
import os
from flask import Flask, request, jsonify, abort, session
app = Flask(__name__)
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY') or \
'e5ac358c-f0bf-11e5-9e39-d3b532c10a28'
#app.route('/login', methods=['POST'])
def user_login():
user = request.form['user']
session['isLogged'] = True
return jsonify({'status': session['isLogged']})
#app.route('/user-info')
def user_info():
if 'isLogged' in session:
return jsonify({'user': 'ali'})
else:
return jsonify({'error': 'Authentication error'})
and our front-end codes should be like this:
mounted() {
this.checkIsLogged();
},
methods: {
checkIsLogged() {
fetch('http://127.0.0.1:5000/user-info', {
mode: 'no-cors',
method: 'GET',
}).then((resp) => {
return resp;
}).then((obj) => {
if(obj.user) {
this.status = true
}
})
},
login() {
let frmData = new FormData(document.querySelector("#frmLogin"));
fetch('http://127.0.0.1:5000/login', {
mode: 'no-cors',
method: 'POST',
body: frmData,
}).then((resp) => {
return resp;
}).then((obj) => {
this.status = obj.status
})
}
}
Everything is normal until I refresh the page. When I refresh the page, I lose the sessions.
Server-side sessions are important for many reasons. If I use localStore or something like that how could be secure I have no idea.
I need some help who worked on similar projects. You can give me suggestions. Because I never worked similar projects.
Other stuff I've read on this topic:
Single page application with HttpOnly cookie-based authentication and session management
SPA best practices for authentication and session management
I'm still confused to about what can I do.
Session handling is something your SPA doesn't really care much about. The session is between the user-agent (browser) and the server. Your vue application doesn't have much to do with it. That's not to say you can't do something wrong, but usually the issue is not with your front end.
That being said it's tough do give an answer to this question because we don't really know what's wrong. What I can do is give you instructions on how you can diagnose this kind of problem. During this diagnosis you'll figure out where the actual issue is and, at least for me, it usually becomes obvious what I need to do.
Step 1)
Use some low level HTTP tool to check the Server response (personally I use curl or Postman when lazy). Send the login request to the server and take a look at the response headers.
When the login is successful you should have a header "Set-Cookie", usually with a content of a "sessionid" or whatever key you're using for sessions.
If you don't see a "Set-Cookie" one of the following is true:
Your server did not start a session and thus did not send a session cookie to the client
there's a proxy/firewall/anti-ad- or tracking plugin somewhere filtering out Cookies
If you see the Set-Cookie Header continue with Step 2, otherwise check the manual in regards to sessions in your chosen backend technology.
Step 2)
Thankfully most modern browsers have a developer console which allows you to do two things:
1) Check your HTTP request headers, body and response headers and body
2) Take a look at stored cookies
Using the first feature (in Chrome this would be under the "Network" tab in the developer console) diagnose the request and response. To do so you need to have the developer console open while performing the login in your app. Check the response of the login, it should contain the Set-Cookie if the login was successful.
If the cookie is not present your server doesn't send it, probably for security reasons (cross-origin policies).
If it is present, the cookie must now be present in the cookie store. In chrome developer console, go to the "Application" tab, expand Cookies from the left menu and take a look at the hosts for which cookies are present. There should be a cookie present which was set in the step before. If not the browser didn't accept the cookie. This usually happens when your cookie is set for a certain domain or path, which isn't the correct one. In such a case you can try to set the domain and/or path to an empty or the correct value (in case of the path a "/").
If your cookie is present, go to step 3
Step 3)
Remember when I said the app has nothing to do with the session. Every request you send either with ajax or simply entering a valid URL in the browser sends all cookies present for this host in the request headers. That is unless you actively prevent whatever library you're using to do so.
If your request doesn't contain the session cookie one of the following is usually true:
the usage of your http library actively prevents sending of cookies
you're sending a correct request but the cookie-domain/path doesn't match the request host/path and is thus not sent along
your cookie is super shortlived and has already expired
If your cookie is sent correctly then your sessions handling should work unless your server doesn't remember that session or starts a new session regardless of an existing session.
I realise this question is quite old and this extensive answer comes way too late, however someone with similar problems may be able to profit from it.

Set-Cookie for a login system

I've run into a few problems with setting cookies, and based on the reading I've done, this should work, so I'm probably missing something important.
This situation:
Previously I received responses from my API and used JavaScript to save them as cookies, but then I found that using the set-cookie response header is more secure in a lot of situations.
I have 2 cookies: "nuser" (contains a username) and key (contains a session key). nuser shouldn't be httpOnly so that JavaScript can access it. Key should be httpOnly to prevent rogue scripts from stealing a user's session. Also, any request from the client to my API should contain the cookies.
The log-in request
Here's my current implementation: I make a request to my login api at localhost:8080/login/login (keep in mind that the web-client is hosted on localhost:80, but based on what I've read, port numbers shouldn't matter for cookies)
First the web-browser will make an OPTIONS request to confirm that all the headers are allowed. I've made sure that the server response includes access-control-allow-credentials to alert the browser that it's okay to store cookies.
Once it's received the OPTIONS request, the browser makes the actual POST request to the login API. It sends back the set-cookie header and everything looks good at this point.
The Problems
This set-up yields 2 problems. Firstly, though the nuser cookie is not httpOnly, I don't seem to be able to access it via JavaScript. I'm able to see nuser in my browser's cookie option menu, but document.cookie yeilds "".
Secondly, the browser seems to only place the Cookie request header in requests to the exact same API (the login API):
But, if I do a request to a different API that's still on my localhost server, the cookie header isn't present:
Oh, and this returns a 406 just because my server is currently configured to do that if the user isn't validated. I know that this should probably be 403, but the thing to focus on in this image is the fact that the "cookie" header isn't included among the request headers.
So, I've explained my implementation based on my current understanding of cookies, but I'm obviously missing something. Posting exactly what the request and response headers should look like for each task would be greatly appreciated. Thanks.
Okay, still not exactly what was causing the problem with this specific case, but I updated my localhost:80 server to accept api requests, then do a subsequent request to localhost:8080 to get the proper information. Because the set-cookie header is being set by localhost:80 (the client's origin), everything worked fine. From my reading before, I thought that ports didn't matter, but apparently they do.

Missing Cookie causing 401

I am making a (forms)authentication module(HTTPModule) for IIS that reads authentication from the login page, sets a cookie and redirects. All works great on all sites and sub applications. Because the module also protects webservices I build in a part that also reads the authorization header. Because these services should also be accessed from other tools.
Now I got to the point I actually protect a webservice, all great and with the auth header to the request I can indeed always get to the webservice but I can ONLY access it with the header active(and after every request I get another cookie).
If I try to access it with my normal login, where I also access other sites under the same protection with then I get redirected back to the login page :S. I really do not understand why this is happening.
PS HttpContext.Current.Request.IsAuthenticated is always false in my module when accessing the service, but my code is:
if(!HttpContext.Current.Request.IsAuthenticated){
if(Forms["Username"] != null){
//do authenticatoin & setCookie and Principle
}
}else{
if(AuthHeader is there){
//do authenticatoin & setCookie and Principle
}
}
Naturally with every request now it authenticates and sets the principle for each request. But why oh why does it not see(send) my cookie while other applications do see it? (with the exact same module)
The OnAuthenticateMethod also does not receive the FormsAuth ticket/cookie but does receive other cookies I set.
Things I already checked:
* web.config authorization is correct.
* Machine keys are set for cookies.
* Cookie names are similar
* .ASPXAUTH cookie does not get send towards OnAuthenticateMethod, but it does get send by the browser in the Cookie header.
I am lost on why this happens.