No persistent session when connecting to API on different host - ruby

I am sending a websocket connection to the API server on a different host:
new WebSocket("ws://localhost:3000")
Whereas my front end is hosted on localhost:8080.
Inside my API's websocket connection handler I'm able to set a key on the session (with Sinatra's enable :sessions) but every time I refresh the html page, the data is lost.
Is there some requirement for sessions that the front end share the same host as the server? Or is there some way I can get around this? By the way, the front end is running on a Webpack server (Node).
I also tried adding a cross_origin allowance for the API's root route http://localhost:3000 and then doing this in the client (this example in coffeescript):
$.get "http://localhost:3000", ->
new Websocket("ws://localhost:3000")
My thinking was that maybe the session needed to be "initialized" over http:// instead of ws:// but it didn't work either. The session didn't work for the $.get "http://localhost:3000" request either. Refreshing the page shows that the session clears each time.

As we've discussed in comments, you probably have a problem with 3rd party session cookies in the browser.
Here's a scheme that you could use to work around it.
Client makes webSocket connection for the first time.
Server sends a webSocket message back with sessionID in it.
Client stores sessionID in a first party cookie (e.g. a cookie in the host web page).
User hits refresh.
Web page checks to see if it has a webSocket session cookie in the cookies for the host page. If so, it constructs a URL for the webSocket connection that includes that session ID `new Websocket("ws://localhost:3000?session=xyslkfas")
When server accepts webSocket connection, it checks the query parameters to see if there is already a session being specified. If so and that session is still valid, it hooks up that connection to that session. If not, it creates a new session and goes back to step 2.

Related

How to set a different session cookie name for every connector?

Currently I set the session cookie name in an embedded Jetty via the follow code:
ServletContextHandler handler = new ServletContextHandler( ServletContextHandler.SESSIONS );
handler.setInitParameter( SessionHandler.__SessionCookieProperty, "SESSIONID" + port );
setHandler( handler );
But then all connectors use the same session cookie name. But I want different session cookie names on different connectors.
The cause of my problem is that
I have HTTP and HTTPS connectors
for a HTTPS connection a secure session cookie is send
It is not possible to override a secure cookie with an HTTP connection in the most browsers.
After a secure cookie from a HTTPS connection it is not possible to work on a HTTP connection anymore until all browser tabs are closed. Some peoples does not close it for weeks. The server send repeatedly new session cookies but the browser does not save it.
I can restart the server, remove the HTTPS connector. All will not work until a browser restart.
A simple fix would be to set different session cookies for different ports or for different protocols. Is this possible for with Jetty?

Session Persistence in Nginx for load balancing

In Nginx, there are three methods regarding session persistence: sticky cookie, sticky route and cookie learn.
Below is a brief explanation about how cookie learn method works, which extracted from Nginx Load Balance:
The cookie learn method. With this method, NGINX Plus first finds
session identifiers by inspecting requests and responses. Then NGINX
Plus “learns” which upstream server corresponds to which session
identifier. Generally, these identifiers are passed in a HTTP cookie.
If a request contains a session identifier already “learned”, NGINX
Plus will forward the request to the corresponding server.
My question is that what if two upstream server generated the same session_id, then how does the prxoy server know which upstream server it should send the request?

What is the difference between cookie and cookiejar?

Today I faced the term "cookiejar" (package net/http/cookiejar). I tried to gather some information regarding it, but got nothing intelligible came out. I know that cookie is key/value pairs that server sends to a client, eg: Set-Cookie: foo=10, browser stores it locally and then each subsequent request browser will send these cookies back to the server, eg: Cookie: foo=10.
Ok, but what about cookiejar? What is it and how does it look like?
As you described in your question, cookies are managed by browsers (HTTP clients) and they allow to store information on the clients' computers which are sent automatically by the browser on subsequent requests.
If your application acts as a client (you connect to remote HTTP servers using the net/http package), then there is no browser which would handle / manage the cookies. By this I mean storing/remembering cookies that arrive as Set-Cookie: response headers, and attaching them to subsequent outgoing requests being made to the same host/domain. Also cookies have expiration date which you would also have to check before deciding to include them in outgoing requests.
The http.Client type however allows you to set a value of type http.CookieJar, and if you do so, you will have automatic cookie management which otherwise would not exist or you would have to do it yourself. This enables you to do multiple requests with the net/http package that the server will see as part of the same session just as if they were made by a real browser, as often HTTP sessions (the session ids) are maintained using cookies.
The package net/http/cookiejar is a CookieJar implementation which you can use out of the box. Note that this implementation is in-memory only which means if you restart your application, the cookies will be lost.
So basically an HTTP cookie is a small piece of data sent from a website and stored in a user's web browser while the user is browsing that website.
Cookiejar is a Go interface of a simple cookie manager (to manage cookies from HTTP request and response headers) and an implementation of that interface.
In general it is a datastore where an application (browser or not) puts the cookies it uses during requests and responses. So it is really a jar for cookies.

Request and session in Servlet

I have very simple question with request and session in web. When I requested a same page page for multiple time from same browser with different tabs or through new window, session ID and session creation time was same.
This I have done from internet explorer. But when in use a different browser like google chrome and access the same page then different session id and session creation time was there. As far as my understanding says http request is stateless.
So, in my case it does not seem to be stateless within same browser as for different http request new thread is created by creating new servlet by container. So I have come to following conclusion:
If request is send from same browser with different tabs opened or through another new window at that time, the request always use the same thread for servlet operation with same session Id. If request is send from different browser then new http request is sent with new session ID.So,my question is then when it is stateless? If the request is send concurrently from different browser? If i declare scope="request"> and scope="session"> in spring then it also follows the same case ? If I am wrong in my understanding please correct me.
Spring
scope="request"
Creates new instance of bean per request.
scope="session"
Creates new instance of bean per session.And maintains instance of bean throughout the session life-cycle
Refer this for better understanding
Irrespective of browsers, Http protocol is stateless. State-fullness is implemented via cookies and session.
When request is sent from the browser, servers creates session and sends back a unique id to the client. And the client uses this id(Cookie) in subsequent request so that server could identify request and associate it with the session.
As far as requests are concerned, server creates separate thread to handle each request irrespective of window, tab or browser. However there will be only one session created per browser.
Note: Latest browsers share the session and the request made from tab, or new window will use the same session. Ex latest IE releases IE7, IE8 and IE9 are well know as Loosely-Coupled IE (LCIE). check this for more details LCIE
When your server application starts a new session, the servlet container sends a Set-Cookie header with a JSESSIONID back to the browser. The browser saves that cookie, and sends it back to the server with each request regardless of what tab you are making the request from. Obvoiusly other browsers don't have access to that cookie, so they will receive another one from the server.
When your server receives a request with a JSESSIONID cookie, it can correlate that request with requests with the same id made earlier. The serlvet container is able to associate different attributes with that id, and persist these attributes between requests. The http session object is basically a container for these attributes, to which your server application has a read/write access. Basically this is how statefullness is implemented with http sessions on top of the otherwise stateless http protocol.
As for the threads: each request can be processed by any random thread, because the session data is not bound to a particular thread. It is the servlet container that maintains the mapping from session id to the session object containing the different attributes. Consequently any random thread can access the session object belonging to the current request based on its session id.
In Spring, request scope means that a bean instance gets newly created for each request, while the lifecycle of the session scoped beans is bound to that of the http session.

Session Management in Tomcat

I have developed a simple web-app with 2 servlets A and B.
I have a few doubts related to session management for the web-app by Tomcat.
NOTE - I have disabled cookies in my web-browser (Chrome) while accessing the web-app.
1.) When the web-app is first hit, Servlet A gets invoked. Servlet A accesses the session from the request and does a simple sysout of the session hashcode. It then does a sendRedirect to servlet B.
[According to my understanding, since this is the first request, Tomcat will send a cookie containing the new session ID back to the browser. However, since we have not "encoded" the redirect URL using HttpResponse.encodeRedirectURL(), the redirect URL will not contain the session ID appended to it. Please correct me if I am wrong here.]
2.) Since cookies are disabled in my browser, it'll ignore the session ID sent back in the cookie and issue a new request to the redirect URL (which also does not have the session ID appended to it).
3.) The new request causes servlet B to be invoked, whoch also accesses the request session and does a sysout of the session hashcode.
What perplexes me is that both Servlets A and B output the same session hashcode, which means that they get the same session from both requests.
How does the second request from the browser map to the same session as before, even though no session ID has been sent ?
Thanks !
There are only 2 ways to pass sessions between requests: Cookie and URL rewrite. If you don't see the session ID in the URL, it must be cookies.
Are you sure the cookie is disabled? It should be easy to see from a HTTP header trace.
Are you certain you've disabled "in memory" cookies? Often browsers will let you disable persistent cookies which are saved to disk, but they'll still allow the transient in memory cookies which only stay resident during a browser session.
I recommend Wireshark for analyzing the HTTP stream. That way you can see the cookies that are sent and received by your browser.
This is strange.
When I tested the application yesterday, it was exhibiting a behaviour similar to what I have described. However, as I test the application now, it behaves perfectly, as I expect it to.
The cause could probably be that I did not restart my browser session after disabling cookies.
Will let you guys know if I experience the same behaviour again.
Thanks for your time guys !

Resources