Getting session data of logged in users in java - java

I am working with servlets. When my user logs in, my application is setting his userId and deviceId in a session variable.
Some other part of my application now needs the list of online people and their userId/ deviceId. Note that a user may have simultaneous logins with 2 devices, so we have 2 deviceIds for the same userId.
How should I approach this situation ? I am not willing to use database for tracking the login/ logout functionalities

Store this information also in HttpServletContext's attribute. This context is global per servlet and can be accsessible by all sessions.
You even can do more. Using HttpSessionAttributeListener you can be notified every time the attribure is added, so if you want to create some kind of monitor application it may be more responsive.

In addition to Alex's response. The header attribute you are looking for is user-agent. Following is the code snippet of accessing browser type from request.
((javax.servlet.http.HttpServletRequest)pageContext.getRequest()).getHeader("user-agent")

In addition to Alex and Suken's responses, assuming the user has a single session you could store the deviceId's in a Map:
String userAgent = (see Suken's response)
String deviceId = request.getParameter("REQUEST_PARAMETER_DEVICE_ID");
Map<String, String> devices = request.getSession().getAttribute("SESSION_ATTRIBUTE_DEVICES");
if (devices == null) {
devices = new HashMap<String, String>();
request.getSession().setAttribute("SESSION_ATTRIBUTE_DEVICES", devices);
}
devices.put(userAgent, deviceId);
This makes sure the multiple devices remain visible and are not overwritten. You still need to expose them like Alex explained if you want to access them at application level.

Related

Java Session Management in multiple tabs of same browser [duplicate]

In a web-application implemented in java using JSP and Servlets; if I store information in the user session, this information is shared from all the tabs from the same browser. How to differ sessions in the browser-tabs?
In this example:
<%#page language="java"%>
<%
String user = request.getParameter("user");
user = (user == null ? (String)session.getAttribute("SESSIONS_USER") : user);
session.setAttribute("SESSIONS_USER",user);
%>
<html><head></head><body>
<%=user %>
<form method="post">
User:<input name="user" value="">
<input type="submit" value="send">
</form>
</body></html>
Copy this code in a jsp page (testpage.jsp), deploy this file in an existing context of a web application on the server (I use Apache Tomcat), then open a browser (FF, IE7 or Opera) using the correct URL (localhost/context1/testpage.jsp), type your name in the input and submit the form. Then open a new tab in the same browser, and then you can see your name (get from the session) on the new tab. Be careful with the browser-cache, sometimes seems that it doesn't happen, but it's in the cache, refresh the second tab.
Thanks.
You can use HTML5 SessionStorage (window.sessionStorage). You will generate a random id and save in session Storage per Browser Tab.
Then each browser tab has his own Id.
Data stored using sessionStorage do not persist across browser tabs,
even if two tabs both contain webpages from the same domain origin. In
other words, data inside sessionStorage is confined to not just the
domain and directory of the invoking page, but the browser tab in
which the page is contained in. Contrast that to session cookies,
which do persist data from tab to tab.
You have to realize that server-side sessions are an artificial add-on to HTTP. Since HTTP is stateless, the server needs to somehow recognize that a request belongs to a particular user it knows and has a session for. There are 2 ways to do this:
Cookies. The cleaner and more popular method, but it means that all browser tabs and windows by one user share the session - IMO this is in fact desirable, and I would be very annoyed at a site that made me login for each new tab, since I use tabs very intensively
URL rewriting. Any URL on the site has a session ID appended to it. This is more work (you have to do something everywhere you have a site-internal link), but makes it possible to have separate sessions in different tabs, though tabs opened through link will still share the session. It also means the user always has to log in when he comes to your site.
What are you trying to do anyway? Why would you want tabs to have separate sessions? Maybe there's a way to achieve your goal without using sessions at all?
Edit:
For testing, other solutions can be found (such as running several browser instances on separate VMs). If one user needs to act in different roles at the same time, then the "role" concept should be handled in the app so that one login can have several roles. You'll have to decide whether this, using URL rewriting, or just living with the current situation is more acceptable, because it's simply not possible to handle browser tabs separately with cookie-based sessions.
The window.name Javascript property, is the only thing that will persist across tab activity, but can remain independent (instead of URL guff).
You shouldn't. If you want to do such a thing either you need to force user to use a single instance of your application by writing URLs on the fly use a sessionID alike (not sessionid it won't work) id and pass it in every URL.
I don't know why you need it but unless you need make a totally unusable application don't do it.
I've come up with a new solution, which has a tiny bit of overhead, but seems to be working so far as a prototype. One assumption is that you're in an honour system environment for logging in, although this could be adapted by rerequesting a password whenever you switch tabs.
Use localStorage (or equivalent) and the HTML5 storage event to detect when a new browser tab has switched which user is active. When that happens, create a ghost overlay with a message saying you can't use the current window (or otherwise disable the window temporarily, you might not want it to be this conspicuous.) When the window regains focus, send an AJAX request logging the user back in.
One caveat to this approach: you can't have any normal AJAX calls (i.e., ones that depend on your session) happen in a window that doesn't have the focus (e.g. if you had a call happening after a delay), unless you manually make an AJAX re-login call before that. So really all you need do is have your AJAX function check first to make sure localStorage.currently_logged_in_user_id === window.yourAppNameSpace.user_id, and if not, log in first via AJAX.
Another is race conditions: if you can switch windows fast enough to confuse it, you may end up with a relogin1->relogin2->ajax1->ajax2 sequence, with ajax1 being made under the wrong session. Work around this by pushing login AJAX requests onto an array, and then onstorage and before issuing a new login request, abort all current requests.
The last gotcha to look out for is window refreshes. If someone refreshes the window while you've got an AJAX login request active but not completed, it'll be refreshed in the name of the wrong person. In this case you can use the nonstandard beforeunload event to warn the user about the potential mixup and ask them to click Cancel, meanwhile reissuing an AJAX login request. Then the only way they can botch it is by clicking OK before the request completes (or by accidentally hitting enter/spacebar, because OK is--unfortunately for this case--the default.) There are other ways to handle this case, like detecting F5 and Ctrl+R/Alt+R presses, which will work in most cases but could be thwarted by user keyboard shortcut reconfiguration or alternative OS use. However, this is a bit of an edge case in reality, and the worst case scenarios are never that bad: in an honour system configuration, you'd be logged in as the wrong person (but you can make it obvious that this is the case by personalizing pages with colours, styles, prominently displayed names, etc.); in a password configuration, the onus is on the last person who entered their password to have logged out or shared their session, or if this person is actually the current user, then there's no breach.
But in the end you have a one-user-per-tab application that (hopefully) just acts as it should, without having to necessarily set up profiles, use IE, or rewrite URLs. Make sure you make it obvious in each tab who is logged into that particular tab, though...
I'll be honest here. . .everything above may or may not be true, but it all seems WAY too complicated, or doesn't address knowing what tab is being used server side.
Sometimes we need to apply Occam's razor.
Here's the Occam's approach: (no, I'm not Occam, he died in 1347)
assign a browser unique id to your page on load. If, and only if, the window doesn't have an id yet (so use a prefix and a detection)
on every page you have (use a global file or something) simply put code in place to detect the focus event and/or mouseover event. (I'll use jquery for this part, for ease of code writing)
in your focus (and/or mouseover) function, set a cookie with the window.name in it
read that cookie value from your server side when you need to read/write tab specific data.
Client side:
//Events
$(window).ready(function() {generateWindowID()});
$(window).focus(function() {setAppId()});
$(window).mouseover(function() {setAppId()});
function generateWindowID()
{
//first see if the name is already set, if not, set it.
if (se_appframe().name.indexOf("SEAppId") == -1){
"window.name = 'SEAppId' + (new Date()).getTime()
}
setAppId()
}
function setAppId()
{
//generate the cookie
strCookie = 'seAppId=' + se_appframe().name + ';';
strCookie += ' path=/';
if (window.location.protocol.toLowerCase() == 'https:'){
strCookie += ' secure;';
}
document.cookie = strCookie;
}
server side (C# - for example purposes)
//variable name
string varname = "";
HttpCookie aCookie = Request.Cookies["seAppId"];
if(aCookie != null) {
varname = Request.Cookies["seAppId"].Value + "_";
}
varname += "_mySessionVariable";
//write session data
Session[varname] = "ABC123";
//readsession data
String myVariable = Session[varname];
Done.
We had this problem and we solved it very easy. I mean easy because no programming involved.
What we wanted to do was to let a user login to multiple account within same browser window without conflicting the sessions.
So the solution was random subdomains.
23423.abc.com
242234.abc.com
235643.abc.com
So we asked our system admin to configure the SSL certificates for *.abc.com rather abc.com
Then with little code change, every time a user try to login, he gets logged in a tab with a random subdomain number. so each tab could have its own session independently.
Also to avoid any conflict, we developed the random number using a hash or md5 of user id.
You can use link-rewriting to append a unique identifier to all your URLs when starting at a single page (e.g. index.html/jsp/whatever). The browser will use the same cookies for all your tabs so everything you put in cookies will not be unique.
I think what you probably want is to maintain navigation state across tabs and not specifically creating a single session per tab. This is exactly what the Seam framework achieves with their Conversation scope/context. Their implementation relies on the fact that a conversation id is propagated with each request and creates the notion of a conversation on the server side, which is something that lies between a session and a request. It allows for navigation flow control and state management.
Although that's mainly aimed at JSF, have a look and check if that's something where you can take some ideas from: http://docs.jboss.org/seam/latest/reference/en-US/html_single/#d0e3620
In javascript, how can I uniquely identify one browser window from another which are under the same cookiedbased sessionId
Essentially use window.name. If its not set, set it to a unique value and use it. It will be different across tabs that belong to same session.
Note: The solution here needs to be done at application design stage. It would be difficult to engineer this in later.
Use a hidden field to pass around the session identifier.
For this to work each page must include a form:
<form method="post" action="/handler">
<input type="hidden" name="sessionId" value="123456890123456890ABCDEF01" />
<input type="hidden" name="action" value="" />
</form>
Every action on your side, including navigation, POSTs the form back (setting the action as appropriate). For "unsafe" requests, you could include another parameter, say containing a JSON value of the data to be submitted:
<input type="hidden" name="action" value="completeCheckout" />
<input type="hidden" name="data" value='{ "cardNumber" : "4111111111111111", ... ' />
As there are no cookies, each tab will be independent and will have no knowledge of other sessions in the same browser.
Lots of advantages, particularly when it comes to security:
No reliance on JavaScript or HTML5.
Inherently protects against CSRF.
No reliance on cookies, so protects against POODLE.
Not vulnerable to session fixation.
Can prevent back button use, which is desirable when you want users to follow a set path through your site (which means logic bugs that can sometimes be attacked by out-of-order requests, can be prevented).
Some disadvantages:
Back button functionality may be desired.
Not very effective with caching as every action is a POST.
Further information here.
Another approach that works is to create a unique window id and store this value along with the session id in a database table. The window id I often use is integer(now). This value is created when a window is opened and re-assigned to the same window if the window is refreshed, reloaded or submitted to itself. Window values (inputs) are saved in the local table using the link. When a value is required, it is obtained from the database table based on the window id / session id link. While this approach requires a local database, it is virtually foolproof. The use of a database table was easy for me, but I see no reason why local arrays would not work just as well.
Spring Session supports multiple session in same browser
Look at the samples and implementation detail
http://docs.spring.io/spring-session/docs/current/reference/html5/guides/users.html
I resolved this of following way:
I've assigned a name to window this name is the same of connection resource.
plus 1 to rid stored in cookie for attach connection.
I've created a function to capture all xmloutput response and assign sid and rid to cookie in json format. I do this for each window.name.
here the code:
var deferred = $q.defer(),
self = this,
onConnect = function(status){
if (status === Strophe.Status.CONNECTING) {
deferred.notify({status: 'connecting'});
} else if (status === Strophe.Status.CONNFAIL) {
self.connected = false;
deferred.notify({status: 'fail'});
} else if (status === Strophe.Status.DISCONNECTING) {
deferred.notify({status: 'disconnecting'});
} else if (status === Strophe.Status.DISCONNECTED) {
self.connected = false;
deferred.notify({status: 'disconnected'});
} else if (status === Strophe.Status.CONNECTED) {
self.connection.send($pres().tree());
self.connected = true;
deferred.resolve({status: 'connected'});
} else if (status === Strophe.Status.ATTACHED) {
deferred.resolve({status: 'attached'});
self.connected = true;
}
},
output = function(data){
if (self.connected){
var rid = $(data).attr('rid'),
sid = $(data).attr('sid'),
storage = {};
if (localStorageService.cookie.get('day_bind')){
storage = localStorageService.cookie.get('day_bind');
}else{
storage = {};
}
storage[$window.name] = sid + '-' + rid;
localStorageService.cookie.set('day_bind', angular.toJson(storage));
}
};
if ($window.name){
var storage = localStorageService.cookie.get('day_bind'),
value = storage[$window.name].split('-')
sid = value[0],
rid = value[1];
self.connection = new Strophe.Connection(BoshService);
self.connection.xmlOutput = output;
self.connection.attach('bosh#' + BoshDomain + '/' + $window.name, sid, parseInt(rid, 10) + 1, onConnect);
}else{
$window.name = 'web_' + (new Date()).getTime();
self.connection = new Strophe.Connection(BoshService);
self.connection.xmlOutput = output;
self.connection.connect('bosh#' + BoshDomain + '/' + $window.name, '123456', onConnect);
}
I hope help you
I've been reading this post because I thought I wanted to do the same thing. I have a similar situation for an application I'm working on. And really it's a matter of testing more than practicality.
After reading these answers, especially the one given by Michael Borgwardt, I realized the work flow that needs to exist:
If the user navigates to the login screen, check for an existing session. If one exists bypass the login screen and send them to the welcome screen.
If the user (in my case) navigates to the enrollment screen, check for an existing session. If one exists, let the user know you're going to log that session out. If they agree, log out, and begin enrollment.
This will solve the problem of user's seeing "another user's" data in their session. They aren't really seeing "another user's" data in their session, they're really seeing the data from the only session they have open. Clearly this causes for some interesting data as some operations overwrite some session data and not others so you have a combination of data in that single session.
Now, to address the testing issue. The only viable approach would be to leverage Preprocessor Directives to determine if cookie-less sessions should be used. See, by building in a specific configuration for a specific environment I'm able to make some assumptions about the environment and what it's used for. This would allow me to technically have two users logged in at the same time and the tester could test multiple scenarios from the same browser session without ever logging out of any of those server sessions.
However, this approach has some serious caveats. Not least of which is the fact that what the tester is testing is not what's going to run in production.
So I think I've got to say, this is ultimately a bad idea.
Storing the timeStamp in window.sessionStorage if it is not already set.
This will give a unique value for each tab(even if the URLs are same)
http://www.javascriptkit.com/javatutors/domstorage.shtml
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage
Hope this helps.
How to differ sessions in browser-tabs?
The most straightforward way to differ sessions in browser tabs is to disallow your particular domain to set cookies. That way, you can have separate sessions from separate tabs. Say you disallow cookies from this domain: www.xyz.com. You open Tab 1, login and start browsing. Then you open Tab 2, and you can login either as a same user or a different one; either way, you will have a session separate from Tab 1. And so on.
But of course this is possible when you have control over the client side. Otherwise, the solutions prescribed by the folks here should apply.
you will need to do
1- store a cookie for accounts list
2- optional store a cookie for default one
3- store for each account with it's index like acc1, acc2
4- put in the url something represent the index of accounts and if not you will select the default one
like google mail domain.com/0/some-url >> 0 here represent the index of account
also you may need to know how to use urlwrite
5- when select a cookie, select it according to your urlpath represent the account index
Regards
I see many implementations which have client side changes to manipulate session id cookies. But in general session id cookies should be HttpOnly so java-script cannot access otherwise it may lead to Session Hijack thru XSS
If it's because each tab will be running a different flow in your application, and mixing both flows causes problems, then it's better to "Regionalize" your session objects, so that each flow will use a different region of the session
This region can be implemented as simply as having different prefixes for each flow, or session object will hold multiple maps (one for each flow), and you use those maps instead of session attributes, the best though would be to extend your session class and use it instead.

Cometd : Multiple tabs for online-users management creating false online-status

I am working on a Spring-MVC based web-app which uses Cometd for chat purposes. For real-time management of which user is online, we are sending notifications when the user is online. So when window is closed, then notifications don't appear and after 30 seconds it is determined that the user is offline or not reachable.
Now the problem happens when user is over multiple browsers. Lets just keep it for 2 now. So, after 10 minutes we are setting user status to 'Away from Keyboard'(AFK). But if the user is online in one browser, then we are getting a blinking status, for few seconds because of the browser in 'Idle Mode', we get a AFK, and from the active machine we get an 'Available' status.
How can we solve this problem? Any ideas, suggestions. I thought of using a boolean flag, and couple with IP address, which will be checked before overwriting the notification, but it has a problem of stale notifications.
This is my code for sending out notifications for online to all listeners(Friends of user).
Code :
#Listener(value = "/service/online")
public void OnlineNotifications(ServerSession remote, ServerMessage.Mutable message) {
Person sender = this.personService.getCurrentlyAuthenticatedUser();
Map<String, Object> input = message.getDataAsMap();
String onlineStatus = (String) input.get("status");
Map<String, Object> output = new HashMap<>();
output.put("status", onlineStatus);
output.put("id", sender.getId());
ServerChannel serverChannel = bayeux.createChannelIfAbsent("/online/" + sender.getId()).getReference();
serverChannel.setPersistent(true);
serverChannel.publish(serverSession, output);
}
Any ideas are welcome. Thanks a lot. :-)
Your application can easily associate multiple devices with the same userName.
You can do this from your SecurityPolicy, just associate the userName string with a List<ServerSession> or whatever data structure fits better your case.
Your online state for a particular userName is therefore a function of all the ServerSessions of this particular userName.
As such, it's a mapping from the userName to a list of online states.
If you imagine user bob logged in from two browsers, the mapping for its online status can be:
"bob" -> ["afk", "online"]
To compute the online status for bob you just run through all the online statuses for each ServerSession and if there is at least one online then it's online, if all are afk then it's away from the keyboard, and so on.
You can implement this logic in several ways (e.g. storing the online status as a ServerSession attribute, use a different data structure, cache the per-user online status, etc.), but you get the idea.
Whenever you get an online status change from one ServerSession, you update your server-side data structure, and then recompute the online status from all ServerSessions for that user, and that is what you send to the other users.

how to detect if user is logged in to site from another browser?

Scenario:
User logs into website.com using firefox. Login credentials are valid, user is directed to member's page.
User tries to log in to website.com using chrome. Login credentials are valid, because use is already logged in using firefox, system will throw error, asks user to close other session to login through chrome.
How can I detect that? Right now I am able to detect it if user only use one browser, but seems to break when user uses two different browsers to log in at different times.
EDIT* I want to say it's more than just using different browsers, the website should not allow multiple people to log in with the same login credentials.
I am assuming your application is j2EE/servlet based. If it is the case, two browsers are independent of each other, hence they have their own sessionId and can function independently, as long as your application does not interfere.
To prevent this scenario, one way to implement is, keep a hashmap of SessionID and UserID in your servlet. You populate this on every successful login, for example via a filter or a valve. When you are populating the hashmap, make a check, to see if any other sessionID is already using this userID. If it is used, check if the corresponding sessionID is still active. If it is not active, allow the login, and delete the stale sessionID. If it is active, terminate the other session and allow the login.
If you're using Spring Security - it may be specified by parameter in the configuration file.
If just plain java - during log-in put user's session id to some storage; when he tries to log-in again you should prohibit it.
But you need to avoid situation when the user will be in storage very long time after closing the browser (one possible solution is short session timeout + keep-alive requests)
In your application, keep a timeout of the user that's updated after each call to the app. You can define the user as 'locked' into a session (for example your firefox session) until either the timeout expires, or the user requests a logout. When you log in on another browse (for example, chrome) it checks to see if there's an active session and, if there is, denies the login attempt.
I'm going to make up a quick example. This isn't even close to production ready and is for illustrative purposes only.
class User {
long lastCheckin;
int userId;
String username;
}
Now, when someone does anything in the app, like viewing a page, you do this
user.lastCheckin = System.currentTimeMillis();
Now, when someone specifically requests a logout, you do this
user.lastCheckin = 0L;
Now, when someone tries to log in, you do this
if(user.lastCheckin + PREDEFINED_TIMEOUT > System.currentTimeMillis()) {
return new LoginResponse(false,"User is active in another session.");
}
You can store a map of logged-in users on an application scope variable like a ServletContext. For example, on your auth servlet, you can probably do something like:
Map<String,String> activeUsers = request.getSession().getServletContext().getAttribute("__ONLINE_AUTHENTICATED_USERS");
//if null, context hasn't been prepared yet, create and attach a new one?2
You have to be careful though. Being an application scope variable, you need to ensure some thread safety and this is something which the servletContext.setAttribute/getAttribute is providing(e.g. those operations are not thread safe). You may be able to handle this by using some sort of application lifecycle listener to 'initialize' the servletContext to have the user map. This way you won't need to worry about the set/getAttribute. You still need to think about the map operations themselves(e.g. use j.u.c.ConcurrentHashMap maybe?).
You also have to take care of cleaning up(e.g. removing from the map) when a user logs out or session times out.
You also have to consider that a user might lock himself out for a long time by this approach(e.g. close browser but do not logout properly, session needs to timeout before the mapping is cleared).
Edit:
You also need to think about scalability and this depends on your application. Are you expecting a million online users? Or only a couple of thousands?

Share Current User Data Between Subdomains on Google App Engine for Java

I am Using Google App Engine for Java and I want to be able to share session data between subdomains:
www.myapp.com
user1.myapp.com
user2.myapp.com
The reason I need this is that I need to be able to detect if the user was logged in on www.myapp.com when trying to access user1.myapp.com. I want to do this to give them admin abilities on their own subdomains as well as allow them to seamlessly switch between subdomains without having to login again.
I am willing to share all cookie data between the subdomains and this is possible using Tomcat as seen here: Share session data between 2 subdomains
Is this possible with App Engine in Java?
Update 1
I got a good tip that I could share information using a cookie with the domain set to ".myapp.com". This allows me to set something like the "current_user" to "4" and have access to that on all subdomains. Then my server code can be responsible for checking cookies if the user does not have an active session.
This still doesn't allow me to get access to the original session (which seems like it might not be possible).
My concern now is security. Should I allow a user to be authenticated purely on the fact that the cookie ("current_user" == user_id)? This seems very un-secure and I certainly hope I'm missing something.
Shared cookie is most optimal way for your case. But you cannot use it to share a session on appengine. Except the case when you have a 3rd party service to store sessions, like Redis deployed to Cloud Instances.
You also need to add some authentication to your cookie. In cryptography there is a special thing called Message Authentication Code (MAC), or most usually HMAC.
Basically you need to store user id + hash of this id and a secret key (known to both servers, but not to the user). So each time you could check if user have provided valid id, like:
String cookie = "6168165_4aee8fb290d94bf4ba382dc01873b5a6";
String[] pair = cookie.split('_');
assert pair.length == 2
String id = pair[0];
String sign = pair[1];
assert DigestUtils.md5Hex(id + "_mysecretkey").equals(sign);
Take a look also at TokenBasedRememberMeServices from Spring Security, you can use it as an example.

Cookie and security in Java (GAE)

Now in my application cookies for users are generated in a certain format containing userID. I want my cookie to be generated randomly after every login so even if cookie were stolen once they would never be used forever by a hacker.
What is the best practice of handling cookies this way? How should I store/retrieve them(hashtable/datastore...)?
Thanks
I would recommend using the built in Java session objects HttpSession, which GAE/J has support for.
Look here for the docs on how to enable sessions on GAE.
You can set the session to expire after a certain time period, or you could store a number in it and verify the session externally.
You can try following parameters:
user id
time to live (milliseconds)
hash for:
user password
user id
remote IP or browser
time to live (exact same as before)
and maybe an predefined string or salt
Join it into one string (like 13413:1826271762:b026324c6904b2a9cb4b88d6d61c81d1) and store it into a cookie like USERID.
On every request you need:
check that specified time is valid (less than current)
load user from database, by specified ID
validate hash signature (against current remote IP/browser and current password)
I agree with Rick, the container designers have done the dirty work of verifying if the request is coming from the same user and you don't want to reinvent the wheel do you?
HttpSession session = request.getSession();
This will create a new session, if one doesn't already exists but if it does it will get you the existing session.
session.setAttribute('key', value);
value can be any Serializable POJO and key is a string.
You can retrieve the stored value within the scope of you application by following code.
Object value = (Object) session.getAttribute('key');
For more information on how to use sessions check Java spec for HttpSessions.

Categories