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.
I need to find a way of reading GET/POST requests from the WEB browser(Network) and retrieve the information like Status, Domain, Size, IP and the most important Timeline.
The main purpose of this is to measure requests count after each action on the WEB page and their execution time. Also this will help me to know if any requests(AJAX/JavaScript) are executing before I want to perform any actions on the WEB page.
Could you please help me with solution?
Assuming you don't want to tie yourself to a particular browser (via plugins or particular dev toolbars), need to capture responses from interactive user events (i.e. via simulated use of a website in a real browser, not dynamically created HTTP calls), and need to automate this, then a proxy server is the way to go.
Something like Browsermob can be set up as a proxy for all Selenium traffic. It can capture the entire content of all requests and responses, and let you generate you a (cross-browser) HAR file that you can then persist, visualise, or query via an API.
Obviously you could automate this, schedule the Selenium test runs, and either produce your own custom metrics with your own Java code; pipe the HAR into a JSON-savvy database for querying (say Elasticsearch) and visualisation, or just save the HARs for offline querying and diffing.
Some example code from the tests:
[...]
proxy.newHar("Test");
HttpGet get = new HttpGet(getLocalServerHostnameAndPort() + "/a.txt?foo=bar&a=1%262");
client.execute(get);
Har har = proxy.getHar();
HarLog log = har.getLog();
List<HarEntry> entries = log.getEntries();
HarEntry entry = entries.get(0);
HarRequest req = entry.getRequest();
[...]
Alternatively you can visualise the output by obtaining the HAR in string form and pasting into http://www.softwareishard.com/har/viewer/. That should give you something that looks very similar to the Network tab, but in a format that's easier to export, screenshot, and print.
Chrome comes with devtools by itself. Just hit 'F12'.
https://developer.chrome.com/devtools
Postman, it's useful for testing web services and API
https://www.getpostman.com/
I'm using Weblogic 10.3.5. I work on a large legacy enterprise application with Struts (1.x) mapped as the default servlet.
Background
A bit of legacy convolution to start: each enterprise customer has a "subscriber ID" which their users must provide at login in addition to their username and password. Subscriber IDs are numeric and always at least four digits, usually five. If you go to mysite.com/, you are presented with a three-field login page: subscriber ID, username, and password.
Our largest enterprise customers didn't like that, so many years ago we introduced skinned login pages: go to mysite.com/12345, where 12345 is your subscriber ID. We'll prepopulate and hide the subscriber ID field, and skin the login page with the enterprise customer's logo and color scheme.
Years later, we had 100+ servlet mappings, one for each subscriber. Every new customer required a software deployment to add the servlet mapping, so our implementations team was hamstrung by the dev team's deployment schedule, which in turn was limited by our large enterprise customers' need to budget time for user acceptance testing.
To address that, we changed the URL: mysite.com/login/12345, where /login/* is mapped to a single servlet that accepts any subscriber ID. We kept the old servlet mappings around so that existing customers didn't have to change the URL, but that left two annoyances:
A few hundred lines of cruft in web.xml
As a developer or QA, it's annoying to have to know whether this is an old subscriber or a new one before you know what URL to use to log in. Try to use the old method for a new subscriber? You get a 404 page.
Here's what I did
We had a pre-existing custom 404 page, correctly defined in web.xml and behaving exactly as expected. I updated it with the following code, right at the top:
<%
if (request.getRequestURI().matches("^/[\\d]{4,}$")) {
// probably someone trying to log in with the old-style URL
response.sendRedirect(String.format("/login%s", request.getRequestURI()));
return;
}
%>
This worked like a charm, until I noticed one oddity:
Here's what's wrong
The very first time I try to visit a URL that should result in a 404 but will be redirected because it matches the regex, it doesn't redirect. With my debugger, I've determined that the reason is that request.getRequestURI() returns "/errors/404error.jsp" rather than "/12345" like I would expect, resulting in the regex not matching and our normal 404 page being served to the user.
My first thought was that something was telling the browser to redirect to the 404 page, but Chrome Dev Tools "Network" tab indicates that is not the case.
After it fails that first time, my change works every subsequent time until the application server restarts.
If I hit /login/12345 first it loads fine. Any subsequent attempt to hit /12345 will work fine, so it seems like it might have something to do with the login servlet not being fully initialized until after the first request. Weblogic is closed source, so I'm not able to dig into what's happening.
Here's my question
I know it's a pretty weird thing I'm doing; I'm open to other approaches. But the question is this: what's causing the different request URI on the first attempt, and how do I fix it? I've scoured the HttpServletRequest object in the debugger and I don't see any indication of the real request URI.
I am making a module for a server software that is allowing support for facebook.
The problem is with the callback URL. If one client start the authorization proccess, then another client starts the proccess at the same time, or before the first user finish. How could I check what user finished first?
I need a way to check what client's callback I'm getting. One solution would be to lock other from register until the first one has finished, but I don't want to do that. Is there another way? I have thought about including ?client=clientid at the end of the callback, but I heard facebook only allows the exact url specified in the app on facebook.
UPDATE
It didn't work to add client="clientid" to the callback. Any other ideas?
After some more searchig I figured facebook will allow a parameter: state. (thanks to #jacob https://stackoverflow.com/a/6470835/1104307)
So I just did ?state=clientId.
For anyone using scribe the code is this:
service.getAuthorizationUrl(null) + "&state=" + clientId;
I think there is no problem on adding and GET parameter like client=clientID. Facebook will redirect you to the URL you have specified and using the REQUEST parameters you can check who completed the request. The problem exist if you have specified URL as http://yoursite.com and pass redirect to http://some-sub-domain.yoursite.com or entirely different location.
if you are using the server-side flow then the oauth 2 flow will be:
redirect user to facebook
facebook then rediects the user to your specified callback
your server uses something like curl to get the access token
your server does some more curl to get maybe more user data or update the user's data
my recommendation would be to set a session cookie in step 1 and simultaneously store this session id on your server. then the session cookie will automatically be sent to the callback url in step 2 and you can identify the session in the database this way.
this will work for all service providers (google, twitter, linkedin, etc) and is the preferred way of maintaining session continuity.
This question already has answers here:
Prevent user from seeing previously visited secured page after logout
(7 answers)
Closed 4 years ago.
I am developing a java web app using servlet, in order to prevent user from hitting the back button to see previous users' info, I have the following code :
protected void processRequest(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
HttpSession session=request.getSession(true);
response.setContentType("text/html");
response.setHeader("Cache-Control","no-cache,no-store");
response.setDateHeader("Expires",0);
response.setHeader("Pragma","no-cache");
......
// if (!User_Logged_In)
session.invalidate();
}
Besides I also have the following code in the file : web/WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
......
<filter>
<filter-name>ResponseHeaderFilter</filter-name>
<filter-class>ResponseHeaderFilter</filter-class>
<init-param>
<param-name>Cache-Control</param-name>
<param-value>private,no-cache,no-store</param-value>
</init-param>
<init-param>
<param-name>Pragma</param-name>
<param-value>no-cache</param-value>
</init-param>
<init-param>
<param-name>Expires</param-name>
<param-value>0</param-value>
</init-param>
</filter>
</web-app>
And the ResponseHeaderFilter.java looks like this :
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class ResponseHeaderFilter implements Filter
{
FilterConfig fc;
public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain) throws IOException,ServletException
{
HttpServletResponse response=(HttpServletResponse)res;
for (Enumeration e=fc.getInitParameterNames();e.hasMoreElements();) // Set the provided HTTP response parameters
{
String headerName=(String)e.nextElement();
response.addHeader(headerName,fc.getInitParameter(headerName));
}
chain.doFilter(req,response); // Pass the request/response on
}
public void init(FilterConfig filterConfig)
{
this.fc=filterConfig;
}
public void destroy()
{
this.fc=null;
}
}
So far it's still not working correctly. The back button will bring up a warning window saying the data has expired, it asks if the user wants to repost it. If you choose yes, it will still display the previous pages info. What am I doing wrong? What's the fix ?
Frank
Yes, I am developing a web app for a PC in public place, if user B hits the back button he might see user A's private info.
I was trying to use session id with servlet, but how to do it, any sample code ?
I also tried the following :
<Html>
<Head>...</Head>
<Body onLoad=document.execCommand("ClearAuthenticationCache","false")>
......
<script type="text/javascript">
// Clear current credentials : Requires IE6 SP1 or later
// document.execCommand("ClearAuthenticationCache");
document.execCommand("ClearAuthenticationCache","false");
</script>
......
</Html>
It works for IE but but Firefox.
How will hitting the back button cause the user to see another user's data? What is your use case? Is it designed for a public terminal, where each user submits data and then leaves? In this case, associate each input with a unique session id. Keep track of valid session ids in your server. Once the input is submitted, remove that session id from the valid ids. If it comes up again, then don't display the information.
Your problem is that you're trying to keep the client from seeing what's on his or her own computer. You can't keep them from looking at their browser cache. You can't keep them from disabling JavaScript (and thus your scripting code). You can't keep them from using a browser that doesn't observe that "repost" convention that you mention.
This is not a problem that can be solved with JavaScript or a server-side solution. That part of why "breaking the back button" is frowned upon: it doesn't actually solve anything.
Breaking the back button is a cardinal sin of web development.
but you could try a bit of java script in the onload that refreshed the details according to the currently logged in session.
It sounds like your real problem is that the re-post works. That would probably be because you:
are trusting credentials from the browser rather than the current session, or
are not checking that the current session is allowed access the data represented by a key/identifier value sent from the browser
I recommend that after a user has logged in you never trust a user name submitted by the browser. Ideally use the security services of a framework like Spring Security but in their absence you can rely on HttpServletRequest.getUserPrincipal().
To make sure the current session is allowed access the data you could use an Access Control List mechanism provided by a framework such as Spring Security or include a WHERE OWNER=? clause in your database queries.
I'm not sure if I understand your problem exactly. Are you concerned about Person A logging off, Person B logs in from the same PC and browser instance, and then you want to prevent Person B from seeing whatever A was viewing?
If so, it should be sufficient to check the credentials of the user on every page load. Check that the current user is authorized to view the data being requested.
I'm not sure I understand your problem correctly, but it sounds like you are allowing rePOSTs.
One approach to prevent resubmission is to use tokens. Put a random token in the form and session. On submission check that the submitted token matches the token in the session
if it does, replace the token in the session with a fresh one and process the request
otherwise stop processing the request).
All of the different browsers have different behaviors and quirks when it comes to how history relates to the cache and the various headers available to control it. Firefox 3 works differently from Firefox 2, re-displaying potentially sensitive data when a user clicks the back button in spite of using caching directives to prevent it. The best solution is to use a session cookie that is not persisted and inform the user of the need to close the browser window after logging out. Especially if they are at a public terminal. Painful, I know, but current browser offerings and the HTTP specification do not provide any mechanisms for dealing with browser history. History may be treated differently than caching by a user agent according to the HTTP specification. See 13.13 History Lists as defined in RFC 2616 Hypertext Transfer Protocol -- HTTP/1.1 for the problem and rationale.
If you're worried about someone seeing what was in a form in a previous page you could use a hidden form for the "real" post and use one that's just for display for the user. When the user submits the display form, you copy all of the fields to the hidden form, clear the display form, then submit the hidden one.
I agree with everyone else - fiddling with the back button this is a bad way to handle protecting information.
I'm not 100% sure this is a fix to your issue, as I don't fully understand how you would get another user's data using back. However, I know that for the web apps I develop I try to exclusively use Redirect After Post to avoid back button and refresh duplicate form submissions.
I think this is as much a user interface challenge as a coding problem. On top of whatever anti-caching techniques you employ, you need to make it clear to the user that they must hit a big, obvious "Logout" button (or equivalent) when they are done.
if this might help. This works for ASP, use an equivalent solution for other languages.
Jeff Atwood described a way to prevent CSRF and XSRF attacks here.
You could use this technique to solve your "users seeing what they should not see" problem.
I had a similar problem in .Net. I added the following javascript to my logout page:
document.execCommand("ClearAuthenticationCache","false");
now if you press the back button you need to authenticate again.