Redirecting from HTTP to HTTPS w/ Simple Auth - ember.js

I was hoping to get some recommendations on how to approach redirecting users from HTTP to HTTPS using an ember initializer with ember-simple-auth.
`import ENV from 'cio/config/environment'`
SSLInitializer =
name: 'ssl'
before: 'simple-auth-cookie-store'
initialize: (container, application) ->
application.deferReadiness()
# Redirect if hitting HTTP and SSL is enabled
if ENV.SSL and window.location.protocol is "http:"
window.location.href = "https:" + window.location.href.substring(window.location.protocol.length)
return false
application.advanceReadiness()
`export default SSLInitializer`
But it seems that the cookie gets invalidated even when the if statement evaluates to true. I've tried several things, including:
before: 'simple-auth'
before: 'store'
application.destroy() within the if statement, before the window.location.href is set
From what I can tell, after debugging. The app does redirect to HTTPS, but then the cookieName is not found in document.cookie. (https://github.com/simplabs/ember-simple-auth/blob/master/packages/ember-simple-auth-cookie-store/lib/simple-auth-cookie-store/stores/cookie.js#L154)
Before this method worked because we had simple snippet in the index.html, but w/ CSP we'd like to keep it in an initializer. Any recommendations?
Thanks!

You really should be forcing a redirect from HTTP to HTTPS from the server as doing it from the client does not add any real security.
Think about it, the user has downloaded the application to their browser from an insecure endpoint and from then on nothing can be trusted. Even a server based redirect is problematic since it relies on the redirect advice from an untrusted endpoint. Users should really be accessing things from an initial trusted starting point otherwise all bets are off. This is known as the secure referral problem and will likely never be solved because of the business model behind SSL certificates.
You also shouldn't really trust cookies from the untrusted HTTP domain in the trusted HTTPS domain unless you have a way to authenticate those cookies on the client. Sharing of cookies between HTTP/HTTPS is covered in RFC 2109 (Section 4.2.2 Set-Cookie Syntax).
This means:
A cookie set with "Secure" will be available only on HTTPS
A cookie set without "Secure" will be available on either HTTP or HTTPS.

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.

Flask session lost after redirect - seems like browser doesn't set the cookie. What am I missing?

I have a web app that makes a POST request to:
https://localhost:5000/processOneTapCredentials
This endpoint sets some data in flask.session, and then returns a redirect to another endpoint (https://localhost:5000/login/success). I can confirm it attempts to set the session. The response headers for the first endpoint (the 302 response) includes:
On the second endpoint, the session is empty though. I see that when the 302 is processed, there is no cookie header set in the headers:
So the flow is:
Web app makes a XHR request (POST) to https://localhost:5000/processOneTapCredentials
https://localhost:5000/processOneTapCredentials sets some flask.session info and returns a 302 to https://localhost:5000/login/success
https://localhost:5000/login/success gets invoked (I see in dev tools), but there is no cookie, so session is empty.
I have set the Flask key correctly, and the session works between redirects in other situations (such as when Flask-dance redirects to authenticate a user). So I must be doing something wrong.
What am I missing?
make sure your app['SECRET_KEY'] is not changing, and if you are redirecting to an external website or redirect from http to https you need to set your SAMESITE policy properly, with a SAMESITE='Lax' cookies are not forwarded, try setting it to None and see it the problem is related to your SAMESITE policy

Why can't I see my (localhost) cookie being stored in Electron app?

I have an Angular app using Electron as the desktop wrapper. And there's a separate Django backend which provides HTTP APIs to the Electron client.
So normally when I call the login API the response header will have a Set-Cookie field containing the sessionId. And I can clearly see that sessionId in Postman, however, I can't see this cookie in my Angular app (Dev tools of Electron).
After some further debugging I noticed a warning sign beside my Set-Cookie in dev tools. It said that the cookie is blocked due to the SameSite being set to Lax. So I found a way to modify the server code to return a None samesite (together with a Secure property; I'm using HTTP):
# settings.py
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_SAMESITE = 'None'
which did work (and the warning sign is gone) but the cookie is still not visible.
So what's the problem here? Why can't (and How can) I see that cookie so as to make sure that the login works in the actual client, not just Postman?
(btw, now both ends are being developed in localhost.)
There's no need to worry. A good way to check if it works is to actually make a request that requires login (after the API has been Postman tested) and see if the desired data are returned. If so, you are good to go (especially when the warning is gone).
If the sessionId cookie is saved it should automatically be included in the request. Unless there's something wrong with the cookie's path; but a / path would be fine.
Why is the cookie not visible: it's probably due to the separation of front and back ends. In Electron, the pages are typically some local HTML files, as one common step during configuration is to probably modify loadURL or something like that in main.js, for instance:
mainWindow.loadURL(`file://${__dirname}/dist/your-project/index.html`);
So the "site" you are accessing from Electron can be considered as local filesystem (which has no domain and hence no cookie at all), and you should see an empty file:// entry in dev tools -> application -> storage -> cookie. It doesn't mean a local path containing all cookies of the Electron app. Although your backend may be on the same local machine, you are accessing as http:// instead of file:// so the browser (Electron) will treat it as an actual web server.
Therefore, your cookies should be stored in another entry like http(s)://localhost and you can't see it in Electron. (Note that the same cookie will work in both HTTP and HTTPS)
If you use Chrome instead to test, you may be able to see it in all cookies. In some cases where the frontend and backend are deployed to the same host you may see the cookie in dev tools. But I guess there're always some reasons why you need Electron to create a desktop app (e.g. Python scripts).
Further reading
Using HTTPS
Although moving to HTTPS does not necessarily solve the original problem, it may be worth doing in order to prevent potential problems and get ready for the publish.
In your case, for the backend, you can use django-sslserver as a temporary solution before getting your SSL, but it uses a self-signed certificate and may make your frontend complain.
To fix this, consider adding the following code to the main process:
# const { app } = require('electron');
if (!app.isPackaged) {
app.commandLine.appendSwitch('ignore-certificate-errors');
}
Now it provides a good way to distinguish between development (unpacked) and production (packed) and only disables certificate check in development in order to make the code work.
Assuming that SESSION_COOKIE_SECURE in your config refers to cookie's secure flag, You ll have to set
SESSION_COOKIE_SECURE = False
because if this flag is set to True the browser will allow this cookie to be set only if you are using an https connection.
PS: This is just for your localhost. Hopefully you ll be using an Https connection in other environments.

Localhost frontend no longer sending cookie to development backend

I'm trying to connect my local frontend to our development backend hosted in aws.
Everything used to work, and I'm going crazy trying to figure out what happened.
The issue is that the request to the backend isn't passing along the cookie we use for authentication.
We have cors setup and it appears to be working correctly. The Options call returns everything I'd expect
.
but the request just doesn't contain the cookie.
I'm setting the cookie via javascript in the frontend code rather than having the server itself set it. This setup used to work idk why it doesn't anymore.
What are the reasons why a browser wouldn't pass a cookie along?
My checklist includes:
ensuring Access-Control-Allow-Credentials is passed back from the Options request
ensure withCredentials is set on the frontend making the request
ensuring the cookie domain is set to /
We recently added some CSRF protection but I disabled that and still can't get the cookie to be sent.
A soapui call to the backend works just fine.
The issue lied in the samesite cookie.
I deployed my development server to explicitly set samesite=none and things are working again.
axios({
method: "get",
withCredentials: true,
});
adding withCredentials:true worked for me

Setting cookies for subdomain

i'm making a web app in a restful way.
For my client side i'm using angularJs, the same is hosted at - lets say -
https://domain.com
My backend is built on spring boot and i call all the resources from a subdomain - lets say -
https://xyz.domain.com
Now when a user logs in , the backend sends an http only cookie to the client.
I can see the cookie in response header but its not being set in the browsers cookie.
After a bit of research, i have tried sending cookie with domain = .domain.com
but that didnt work either.
Is there a way i can set cookie coming from xyz.domain.com for my client side at domain.com
(Note - i'm not using www.domain.com )
Any help or clue would be great.
Thank you for going through my question.
The problem you're describing is related to cross domain cookie policies. I don't know your exact use-case, but looking at CORS and P3P headers should give you a good start. As an option, you can try setting your cookie manually via Javascript.
Making CORS working isn't enough, you also need to enable withCredentials in angular.
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials
Example:
angular.module('example', []).config(function ($httpProvider) {
$httpProvider.defaults.withCredentials = true;
});