What are the different ways to track the session in servlet. Is it is possible by using hidden files ?
There are three ways
hidden form fields
cookies
url encoding.
One of the ways is to use HttpSession You can create session using
HttpSession session = request.getSession();
or you can use HttpSession session = request.getSession(true). Both statements mean that If there is associated session with this user, then return that one or create a new session. If false is passed, then new session is not created.
sessions can be maintained in the following ways
hidden form field.
cookies
encodeURL
session object
have a look at here link
The different ways to track session in servlet are:
Using the session API:
a sample code for that is:
//store the username object in the session-scope
HttpSession session = request.getSession();
session.setAttribute("username",username);
To retrieve the session attribute,use the session.getAttribute()
Username username = (Username) session.getAttribute("username");
Using the cookies API:
sample code:
String name = request.getParameter("username");
Cookie c = new Cookie("username",name);
response.addCookie(c);
It should be noted that a major disadvantage of using cookies for session management is that sometimes the client might have cookies turned off.
Using URL-Rewriting:
The URL-rewriting strategy is not as transparrent as the cookie strategy.
It could be implemented in a form as below:
//present the form
out.println("<form action='"+response.encodeURL("login.")+"'");
Hidden form field can also be used.
Yes,it is possible with hidden fields.
And there are other ways too
User authorization
Hidden fields
URL rewriting
Cookies
Session tracking API
These are the ways to tracking Session
1.With cookies
2.With URL rewriting
3.With SSL information
For more details click here
Session can be maintained in flowing ways
Hidden form field :- Use full when the form are generated dynamically
cookies
URL rewriting
HttpSession
The HttpSession depend on the cookies. It uses cookies to store the session id in client system.
Suppose a servlet that implements HTTP sessions receives HTTP requests from three different clients (browsers). For each client request, the servlet must be able to determine the HTTP session to which the client request pertains. Each client request belongs to just one of the three client sessions being tracked by the servlet. Currently, the product offers three ways to track sessions:
With cookies
With URL rewriting
With SSL information
There are various session tracking mechanisms
Session API
Cookies
URL Rewriting
Hidden Form Fields
Hidden Form Fields ->
In this case, we use hidden text-field for maintaining the state of a user.
It is just programmer's trick to remember client information.
Related
I have created a basic spring security authentication using UserDetailsService and now I am able to validate user. However, I don't understand how to achieve below things:
Once a user is logged in, when next request comes how and where do I check if the request is coming from the same logged in user or other logged in user?
I know the concept of Spring interceptors where I can intercept all incoming request. But is there something in spring security that does this?
How can I start a session after logging in and store values in session for that user?
I browsed through existing answers but most of examples are for logging in.
I would appreciate if someone can give me examples.
EDIT:
I think I should use session scoped beans in order to maintain user's session contents rather than manipulating httpsession directly.
I think you really need to spend some time reading the Spring security documentation and over all JSP, servlet and MVC architecture. You have several misunderstandings,
After authentication, you don't need to start a session it was already there when the request came. Remember request.getSession()we get the session from the request and I am really NOT aware of any other way i.e. instantiating session object and assigning it to request/response. After successful authentication spring automatically sets a SPRING_SECURITY_CONTEXT attribute in session and this variable is later used to determine whether user is already authenticated or not (Spring does that for you, you don't need to use this attribute).
In spring security we set an authentication entry point which has information about login page url and FORM_LOGIN_FILTER which has information about login processing url, login success url and login failure url among few other things.Every request whose session doesn't have SPRING_SECURITY_CONTEXT and auth attribute gets redirected to login page url.
I could give the code directly but it would be great if you read at least few pages of Spring documentation here. Once you understand the concepts and are still not able to solve the problem. Edit your question with detailed problem and we will try to fix it.
At first you need to create an Authentication object using current HttpRequest as below:
public class SessionService{
public Authentication getSession(HttpServletRequest request) {
HttpSession session=request.getSession();
SecurityContext ctx= (SecurityContext) session.getAttribute("SPRING_SECURITY_CONTEXT");
Authentication auth=ctx.getAuthentication();
return auth;
}
}
Then, you can retrieve the session details from this Authentication object by passing the current HttpRequest as follows:
Authentication auth = sessionService.getSession(request);
The above auth object contains the details that you need.
I read lot of articles which says that there are different ways to manage the session like cookies, hidden form fields, url rewriting and jsessionId.
But when I do
HttpSession session = request.getSession();
Which method is actually used internally?
According to the servlet 2.4 specification:
Session tracking through HTTP cookies is the most used session
tracking mechanism and is required to be supported by all servlet
containers... To fulfill this requirement, Web containers commonly
support the URL rewriting mechanism.
Basically the session tracking (i.e. to keep the user interaction and sending the data ) can be maintained by 4 ways like HttpSession,cookies,hidden field and URL rewriting.
It depends on your requirement , which it needs to use.
If you are using HttpSession then you need to go for
HttpSession session = request.getSession(true);
As Cookies are client side.
Hidden fields are the form data you need to send to by request to servlet.
URL rewriting is used for sending the data using href or any link (usally GET method).
Session is used for secure and state full transaction.
Which method is actually used internally?
Its recommended to use HttpSession , if you want to track the request data over the application, until unless you invalidate that session. Jsessionid is a part of HttpSession. Internally Session is using unique Jsessionid for each session you are creating.
Hope it will help you.
The answer is that it doesn't depend on Java. It depends on the specific servlet container you are using and possibly the browser as well. If the brower won't accept cookies for example the container may be forced back to using URL rewriting.
I'm developing a single page jQuery & Backbone.js web app. The backend is a JBoss 6 application server.
Until now we had the following structure:
There is only one servlet (front controller). Every request from the JavaScript client goes through here.
In the servlet - at the first request of a certain JS client - I make a look p to a stateful session bean. For the next requests of this client, I store the result of the look up in an HTTP session container. So every JS client has exactly one stateful session bean. This connection is kept by a session cookie.
Now I have an additional requirement:
When the user has two browser tabs (in one browser), they should have two isolated instances of the web app in every browser tab. Because of that I have a problem with session cookies because this session cookie is for all browser tabs.
I have to change the structure so that:
The servlet has to generate a new session ID for the first request of a certain JS client. This session ID is communicated to the client.
With every POST to the backend the JS client has to send this session ID.
My question is:
Until now I saved the result of the look up in an HTTP Session object and I hadn't to think about generating a session ID. But now I have to store this somewhere else, where?
Has anybody experience with this kind of setting and can help me?
Update:
Thank you BalusC for this very interesting approach.
When I understood you well, this means:
All individual JS clients of the tabs of one browser share one HTTP session object. And in this HTTP session object, every tab has its own entry point. That sounds really good. So I still can use the whole HTTP session infrastructure and don't have to reinvent the wheel.
Autogenerate an unique value on the initial GET request which you store and pass around on every subsequent postback as a hidden input value. Use this unique value as identifier of the session attribute representing the view-scoped data.
During the 1st request on a brand new session, do:
Map<String, ViewData> viewScope = new HashMap<String, ViewData>();
session.setAttribute("viewScope", viewScope);
(the ViewData represents the view-specific data you'd like to track across postbacks on the same view)
During every GET request, do:
String viewDataId = UUID.randomUUID().toString();
viewScope.put(viewDataId, new ViewData());
request.setAttribute("viewDataId", viewDataId);
During generating the HTML, do:
<input type="hidden" name="viewDataId" value="${viewDataId}" />
During every POST request, do:
ViewData viewData = viewScope.get(request.getParameter("viewDataId"));
// Get/set view-specific data in there.
Make sure that jQuery also passes this hidden input around (which shouldn't be a big problem if you already properly use $(form).serialize() or e.g. AjaxForm plugin to ajaxify the forms).
If you're familiar with Java EE's MVC framework JSF, then it may be useful to know that its #ViewScoped annotation works roughly the same as described above. See also a.o. How to choose the right bean scope?
You can use session tracking with URL rewriting. See here:
Session shared in between tabs
I'm using a URL with a jsessionid, eg.
http://localhost:8080/myservlet;jsessionid=123
Yet whenever I read the session ID in the HttpServletRequest the value is never 123, but instead a generated session ID, eg. B663A96D3FBC84B4A427C0810EAB9073.
Why is my jsessionid being ignored?
That's because you specified a session ID for which no concrete HttpSession object exist in server's memory. In other words, the given session ID is unknown/invalid. You need to specify a session ID which refers a valid and existing HttpSession object in server's memory.
Assuming that you do have a valid HttpSession with ID B663A96D3FBC84B4A427C0810EAB9073 currently in server's memory, then the following link will work and give the enduser access to exactly that HttpSession:
http://localhost:8080/myservlet;jsessionid=B663A96D3FBC84B4A427C0810EAB9073
My guess would be that most application servers these days default to using cookies for session tracking, not URL rewriting. So if your request contains both a session cookie and a JSESSIONID in the URL, it will probably use the one from the cookie. Check the documentation of your appserver for how to configure this.
I've always taken for granted the JSESSIONID cookie created for every fresh request for a given client when developing applications using the servlet specification. But after giving it a bit of thought, isn't is more logical for the servlet container to create a cookie header only after the session has been requested and created in code? For clients who have their cookies disabled, won't it end up creating a new HttpSession for each request made?
Please let me know if the question is still unclear so I can edit it. TIA.
A new Session will not be created by the Servlet container by default unless the Servlet actually creates it explicitly. Just because in the Header a JSEESIONID is being populated does not mean that there has to be a seesion on the server. An exception to this is in JSPs that by default create a Session if one is not there unless <%# page session="false" %>
As far as not having cookies turned on:
A web container can use several
methods to associate a session with a
user, all of which involve passing an
identifier between the client and the
server. The identifier can be
maintained on the client as a cookie,
or the web component can include the
identifier in every URL that is
returned to the client.
If your application uses session
objects, you must ensure that session
tracking is enabled by having the
application rewrite URLs whenever the
client turns off cookies. You do this
by calling the response's
encodeURL(URL) method on all URLs
returned by a servlet. This method
includes the session ID in the URL
only if cookies are disabled;
otherwise, it returns the URL
unchanged.