Cross language and server http session variables - java

I have one problem of retrieving http session variables. I have two sever, one jetty and one apache. And two languages PHP in Apache and Java in jetty. When the user login to the website, his or hers profile ID is stored as Session variable in the Apache server in PHP. Can I somehow retrieve this session variable from the Jetty server using Java?

For cross server session you can keep session in cookies. But you need to make sure that these cookies are encrypted using some strong algorithm and key.
If you want to store only user ID. Then you can store ID as it is if its public ID and store a signature along with that, if ID is tempered with you can detect it using signature.
Create two cookies after authentication
1. One contains ID and
2. other contains signature of ID like using function in php called hmac_hash
hmac_hash
Whenever you get a request which needs authentication.
1. Using ID and same secret generate same signature back.
2. Check if the signature you generated is same as one you got in cookie.
Warning: Slight mistake can make data public.
Warning 2: Large cookie will make site a bit slower.

were it me, i'd be tempted to override the session handlers in php and store the session stuff in a database. see http://us2.php.net/manual/en/function.session-set-save-handler.php
that way you control how the session variables are stored and where they are stored. you can read the session handle from the cookie or whatever in either language and write your own stuff for the java side.

Related

Encryption algorithm for URL Identifiers

I am working on a Spring Web application, and came across a scenario that requires passing an identifier in the URI (GET over HTTPS), for example: https://www.targetdomain.com/services?id=123. This URI appears on the end user browser, and my concern is that, anyone can tamper this identifier "123" that is linked in my database as primary key in one of the table.
One way to resolve this issue could be to save this in user's session (HTTPSession), another could be to encrypt it and throw that in browser as https://www.targetdomain.com/services?id=jk3434jj123jkh23jh213h. Once end user clicks on the link, I can decrypt that on the server side to retrieve the identifier.
I am new to encryption, and I wanted to know what suitable encryption algorithm, I should use to encrypt this identifier before printing that on browser, so that I can retrieve it on the server
I came across some post (for example - encrypt and encode URL parameters spring mvc) where a working code is presented using "AES/CBC/PKCS5Padding" as cipher. Does that looks a good solution for this use case?
The most secure solution would be to manage the parameter in the session as you described, if that's an option. That way it's all on the server and it's protected against an attacker having access to a user session in a browser (but not to the server). If you can do this, it's probably the right thing.
However, sometimes you need to pass through the browser. For whatever you send to the browser, you might have two distinct requirements:
You might want that the user cannot read it, for which the solution is encryption. In case of an id, this is probably less relevant, but your ids might also be sensitive in some way, only you can tell.
You might want that the user cannot modify them, and for this you need message authentication. This requires a secret on the server, used to generate an authentication code for your parameter, that upon receiving them back can be verified (using the secret again).
Note that these are two separate things, encrypted messages are not necessarily authenticated, and authenticated messages are not encrypted.
So if you only care about message authentication, you could add an authentication code as a separate parameter, generated with eg. HMAC, and then check that upon getting your parameter back.
Or depending on your requirements, you can choose an authenticated encryption (AEAD), which provides both features in one. Such an algorithm is eg. AES in GCM mode. (AES-CBC mentioned in your question is not an authenticated mode for AES.)
Note that you would have to consider replay attacks as well. If you only authenticate or encrypt the parameter itself, a user can observe such encrypted parameters in other sessions for example, and replay those in his own session. One standard solution to this is to include a timestamp as well so that such secure parameters are also timebound, and even this in your specific scenario might not be enough. For example if access control is based on such an authenticated parameter, an observed authenticated, timebound parameter in another user's session might be used to access data in the current user's session (albeit this would be harder to actually exploit).
Or you can still just do it through the session... :)

Storing data as a cookie in the browser vs. session

I am trying to learn more about JAVA web development. I am mainly focused on trying to understand how data that a user enters, maybe through the course of filling out a multipage form, is managed as the user moves from page to page.
From what I have gathered, you can store data within the session on the server side. I am also learning about cookies which are stored within the browser. Is there a general rule that is used to determine what data should be stored in a cookie vs. when you should store data in a session (session.setAttribute), or are these completely different concepts?
Thanks
The basics of session/cookies are like this.
A session is typically a way for a server to store data about a user. This can be done in a variety of ways from memory, file to database. This session can be used by you store pretty much anything you need to have as the user bounces around your site. It is assigned an ID (the session ID) which you don't usually need to worry about too much. In most web languages you can easily access the user session with some functions without dealing with IDs.
Now since the web is stateless - meaning there is really no way to know that user that visited page A is the same as the one that visited page B then we want to make sure that the user carries their session IDs with them. This can be done in a variety of ways but the most common one is through the use of a session cookie which is a special cookie automatically set by the server that is solely there for passing the session around. It can also be passed in the URL (I'm sure you've seen things like index.php?sessid=01223..) as well as headers and so on.
When most people talk about adding info to a cookie they are not talking about session cookies but about a custom cookie that you specifically set. The only reason that you would want to do that is if you needed to store info beyond the life of the session (which ends when the browser is closed). A good example of that is the "remember me" feature of many sites.
So use sessions unless you need to have something last a long time.
Yes. There are a few rules actually. For one, cookie data is sent by the browser on every request; session data is kept on the server (and not re-transmitted every request). However, usually the session id is used with a coookie. This enables the server to identify the client.

Using sessions in GAE/J

I'm having a hard time piecing together the various threads I've read on the topic, so I'd love to know if I'm on the right track before I get too far. I'm trying to make persistent logins using sessions and cookies and the like. At this point, I feel I've got my head around the login sequence, right now I just have a user db, but I'll try to tackle OAuth at a later date.
Login:
User enters credentials
Creds are sent async to server (ideally via SSL, eventually)
Passwords are never stored, only hashes are kept
If creds are OK, server sends the value of this.getThreadLocalRequest().getSession().getId() back
Callback method saves sessionID in a cookie and modifies the UI accordingly
(logout method clears the cookie and calls this.getThreadLocalRequest().getSession().invalidate())
I get lost when I want a user to be able to come back and pick up where they left off without having to log back in. I get the sessionID back from the cookie (if there is one), and then I somehow need to ask the server to verify it's valid. Is there a method that takes a session ID and returns whether it's a valid session? Or do I somehow tell the current session to use that ID?
The end goal is that I want to include the session ID in RPC calls that should be restricted to logged in users, and the server side methods will validate the sid received by RPC before running. I don't have to keep a running list of valid sids, right? That's already being handled by GAE (yes, I have the <sessions-enabled> set)
getSession returns a session object that can be used for persistent storage across requests. It already uses cookies to persist the session ID between requests. You don't need to get the session ID and store it separately in another cookie.
If you want to associate data with the user in the DB, either associate it with the session ID (eg, include the ID in the entity and look it up by ID) if you want it to be scoped to just the current session, or associate it with the user ID.
Unless you have a really, really compelling reason to invent your own user management, though, you really should be using the built in Google Accounts or OpenID support. You're not doing your users a service by forcing them to create yet another account for your site.
this.getThreadLocalRequest().getSession(false)
Returns the current HttpSession associated with this request and returns null in case it has no valid HttpSession.

Google App Engine Java - Keep Session alive after users close browser (remember me function)

We can enable session by setting sessions-enabled to true in file appengine-web.xml. However, the session implemented by GAE is not persistent after closing browsers. My question is how to keep the session persistent so "remember me" function can be implemented. There are a number of Python libraries but I couldn't find any for Java. Thank you very much for your help!
The common way to do this is to associate a unique random key to your users, store it in a persistent cookie (use Cookie.setMaxAge() with the number of seconds you want this cookie to stay valid), and send this cookie to the user.
Look in the javadoc for HttpServletResponse.addCookie (to send a cookie to the user), and for HttpServletRequest.getCookies() (to get back the cookie from the client).
Since we can't mark a comment as an answer (and some people are likely to miss it entirely), I'll point out the specific solution per JB above. Get the session id using this.getThreadLocalRequest().getSession().getId(). Store the sid in a cookie as JSESSIONID with Cookies.setCookie(...)
This overwrites the cookie created by GAE, keeping the same session id, but applying your expiration time. Be careful how you use this, though, it's prone to attacks (look up session hijacking and XSS).

Custom ID in session handling by Java Servlet API

Is it possible to assign a custom ID to a HTTP session through Servlet API?
I know that session handling from any application server, Tomcat for example, it's enough good to generate unique IDs. But I have custom unique session IDs based on information per user and time, so it won't be repeated.
And I looked at every documentation about session handling but nowhere I find what I need.
It's a requirement for a project, so if it's not possible, I need to know the reasons (or it's only not available through API?).
If you are using Tomcat, you may be able to create a custom session manager (see this discussion). You would then have access to the Tomcat Session object and could call setId.
The servlet API does not support creating your own cookie value. In fact, it does not guarantee that sessions are maintained via cookies... it specifically states that they can be maintained via a mechanism such as "URL Rewriting". It DOES guarantee that the session is maintained in some fashion, and that pretty much requires some sort of unique ID which is passed to the browser and returned, but no mechanism is provided in the Servlet API for servlet code to control what value is used. Nor do common servlet containers that I know of (such as Tomcat) provide a means for controlling this value.
However, none of this should be a problem for you if I understand your requirements properly. Just because Tomcat (or whatever servlet container you use) is creating a unique ID based on its own algorithms (that contain things like cryptographically secure random number generators to prevent "guessing" of session IDs), doesn't mean that you cannot create a SEPARATE ID which meets your requirements (based on user and time, unique across all sessions... whatever you need). This ID can be stored in the session (if that's all you need), or can be stored on the browser in a separate cookie (if you need it maintained across sessions). The only effect would be that the browser was storing TWO cookies -- and most websites store many more cookies than that!
Um...if you have the code to generate a unique ID, you can just do this:
/**
* The String key of the user id attribute.
*/
public static final String USER_ID_KEY = "userIdKey";
// Set the user attribute (createUniqueUserId's parameters and return type are up to you)
httpSession.setAttribute(USER_ID_KEY, createUniqueUserId());
// Retrieve the user attribute later
httpSession.getAttribute(USER_ID_KEY);
The HttpSession interface also provides a getId() method, which is documented here (copying the documentation for reference):
public java.lang.String getId()
Returns a string containing the unique
identifier assigned to this session.
The identifier is assigned by the
servlet container and is
implementation dependent.
Returns: a
string specifying the identifier
assigned to this session

Categories