Missing Cookie causing 401 - web-services

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.

Related

Keystone session cookie only working on localhost

Edit:
After investigating this further, it seems cookies are sent correctly on most API requests. However something happens in the specific request that checks if the user is logged in and it always returns null. When refreshing the browser a successful preflight request is sent and nothing else, even though there is a session and a valid session cookie.
Original question:
I have a NextJS frontend authenticating against a Keystone backend.
When running on localhost, I can log in and then refresh the browser without getting logged out, i.e. the browser reads the cookie correctly.
When the application is deployed on an external server, I can still log in, but when refreshing the browser it seems no cookie is found and it is as if I'm logged out. However if I then go to the Keystone admin UI, I am still logged in.
In the browser settings, I can see that for localhost there is a "keystonejs-session" cookie being created. This is not the case for the external server.
Here are the session settings from the Keystone config file.
The value of process.env.DOMAIN on the external server would be for example example.com when Keystone is deployed to admin.example.com. I have also tried .example.com, with a leading dot, with the same result. (I believe the leading dot is ignored in newer specifications.)
const sessionConfig = {
maxAge: 60 * 60 * 24 * 30,
secret: process.env.COOKIE_SECRET,
sameSite: 'lax',
secure: true,
domain: process.env.DOMAIN,
path: "/",
};
const session = statelessSessions(sessionConfig);
(The session object is then passed to the config function from #keystone-6/core.)
Current workaround:
I'm currently using a workaround which involves routing all API requests to '/api/graphql' and rewriting that request to the real URL using Next's own rewrites. Someone recommended this might work and it does, sort of. When refreshing the browser window the application is still in a logged-out state, but after a second or two the session is validated.
To use this workaround, add the following rewrite directive to next.config.js
rewrites: () => [
{
source: '/api/graphql',
destination:
process.env.NODE_ENV === 'development'
? `http://localhost:3000/api/graphql`
: process.env.NEXT_PUBLIC_BACKEND_ENDPOINT,
},
],
Then make sure you use this URL for queries. In my case that's the URL I feed to createUploadLink().
This workaround still means constant error messages in the logs since relative URLs are not supposed to work. I would love to see a proper solution!
It's hard to know what's happening for sure without knowing more about your setup. Inspecting the requests and responses your browser is making may help figure this out. Look in the "network" tab in your browser dev tools. When you make make the request to sign in, you should see the cookie being set in the headers of the response.
Some educated guesses:
Are you accessing your external server over HTTPS?
They Keystone docs for the session API mention that, when setting secure to true...
[...] the cookie is only sent to the server when a request is made with the https: scheme (except on localhost)
So, if you're running your deployed env over plain HTTP, the cookie is never set, creating the behaviour you're describing. Somewhat confusingly, in development the flag is ignored, allowing it to work.
A similar thing can happen if you're deploying behind a proxy, like nginx:
In this scenario, a lot of people choose to have the proxy terminate the TLS connection, so requests are forwarded to the backend over HTTP (but on a private network, so still relatively secure). In that case, you need to do two things:
Ensure the proxy is configured to forward the X-Forwarded-Proto header, which informs the backend which protocol was used originally request
Tell express to trust what the proxy is saying by configuring the trust proxy setting
I did a write up of this proxy issue a while back. It's for Keystone 5 (so some of the details are off) but, if you're using a reverse proxy, most of it's still relevant.
Update
From Simons comment, the above guesses missed the mark 😭 but I'll leave them here in case they help others.
Since posting about this issue a month ago I was actually able to work around it by routing API requests via a relative path like '/api/graphql' and then forwarding that request to the real API on a separate subdomain. For some mysterious reason it works this way.
This is starting to sound like a CORS or issue
If you want to serve your front end from a different origin (domain) than the API, the API needs to return a specific header to allow this. Read up on CORS and the Access-Control-Allow-Origin header. You can configure this setting the cors option in the Keystone server config which Keystone uses to configure the cors package.
Alternatively, the solution of proxying API requests via the Next app should also work. It's not obvious to me why your proxying "workaround" is experiencing problems.

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

Use same ss-id cookie across all subdomains - ServiceStack

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.

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.