I am new to Servlets and sessions.
I am building a website using Servlets and JSP's.I am using Http connection.
I am using Sessions,After login into my website session is created ,When i click the browser back button again and again ,i can go to the login screen and again on clicking the browser forward option i can enter into the website without any issues.
My expectation is When the browser goes to the login screen,the session should be expired and it should again ask for new password.
Is there anyway i can do it with this http connection.
You can invalidate the session in your show login servlet:
....
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate();
}
This solution works both for first visit and return visits.
If you want to invalidate the session only if this is not the first visit you can do that:
In login servlet
HttpSession session = request.getSession(false);
session.setAttribute("loggedUser", loggedUser);
In show login servlet
HttpSession session = request.getSession(false);
if (session != null) {
if (session.getAttribute("loggedUser") != null) {
session.invalidate();
}
}
Note if you use a standard login process you can use instead in the show login method
HttpSession session = request.getSession(false);
if (session != null) {
if (request.getRemoteUser() != null) {
session.invalidate();
}
}
Some ideas would be:
Check on your login.page, before you do anything other, if your mySession != null. You can get your session like HttpSession mySession= request.getSession(false);
If your session is not null, your user already logged in once. In this case you can invalidate your session mySession.invalidate();
Overall it should looke like that:
HttpSession mySession = request.getSession(false);
if (mySession != null)
{
mySession .invalidate();
}
Another problem could be the browser chaching your page.
An idea how to disable this in the clients browser can be found in this question.
A third way could be using javascript. You could add a listener on browser back. An question with anser is already avalibale here.
Hope that helps
Related
I made an app and I want to get cookies as soon as there is new session. I tried it with the session listener but didn't work. I tried it with the request listener but got a null in cookies array.
this is the code from request listener and it gets me null every time
public void requestInitialized(ServletRequestEvent sre) {
HttpServletRequest req=(HttpServletRequest)sre.getServletRequest();
if(req.getSession().isNew())
{
Cookie c[]=req.getCookies();
try
{
for (Cookie co:c)
{
System.out.println(co.getName());
System.out.println(co.getValue());
}
}
catch(Exception e)
{
System.out.println("error: "+ e.getMessage());
}
}
}
The HttpServletRequest.getCookies() returns cookies provided in the request - as described in the HttpServletRequest's javadoc.
When servlet container creates a new session, it usually means that either no cookies were provided (session is unknown) or there was a session cookie, but the session itself has been expired.
Please check section 7.1 Session Tracking Mechanisms of the Java™ Servlet Specification for the complete explanation of the standard session semantics and lifecycle.
I figured it out , the problem was with chrome. it consider the cookie as session cookie until I added header "Expires" to the response
This question already has answers here:
How to redirect to Login page when Session is expired in Java web application?
(9 answers)
Closed 6 years ago.
HttpSession session = request.getSession();
User user = (User)session.getAttribute("user");
if(user == null){
response.sendRedirect("login.jsp");
}
System.out.println(user);
I am writing this code in a servlet and deploying it in Tomcat Server. After the session expires, session is automatically created but the "user" attribute becomes null. But the page is not redirected to "login.jsp" and "null" gets printed on the console.
I am using MyEclipse IDE.
That's because the call to getSession() without a boolean parameter will create another session.
Do this: HttpSession session = request.getSession(false);
Also, make sure you place this snippet before any other headers are sent to avoid confusing the browser.
However, for a more comprehensive solution, see #BalusC's comment
On the server side, after a successful logon, I execute :
HttpServletRequest request = this.getThreadLocalRequest();
HttpSession session = request.getSession();
session.setAttribute("user", subject.getUser().getId());
session.setAttribute("logged", true);
I then assume that the user is logged in. When the user navigates to a secure page in order to save or delete a record from my database, I run this code.
HttpServletRequest request = this.getThreadLocalRequest();
HttpSession session = request.getSession();
if (session.getAttribute("user")!=null && session.getAttribute("logged"))
{
//delete a record using the authority of the user.
}
My concern is that a client can tamper its browser cookie with a different user id. The database request would be initiated with a different user, skipping the login process.
Can java session identify tampering, or should I digitally sign the session by including this line
session.setAttribute("signature", hash(secretkey + subject.getUser().getId());
then verify that the signature is valid before changing the database.
if (session.getAttribute("signature").equals(hash(secretkey + session.getAttribute("user"))
{
//delete a record using the authority of the user.
}
Have you examined your cookies? Are you actually keeping the user-id in a cookie, and if yes, what for?
The server side session object can't be accessed from the client side, that would be a huge security problem.
If your code is correct, there's no reason or advantage in using a hash.
This question already has answers here:
Prevent user from seeing previously visited secured page after logout
(7 answers)
Closed 7 years ago.
HttpSession session = request.getSession();
try
{
session.removeAttribute("logonSessData");
session.invalidate();
String pageToForward = request.getContextPath();
response.sendRedirect(pageToForward);
}
catch (Exception sqle)
{
System.out.println("error UserValidateServlet message : " + sqle.getMessage());
System.out.println("error UserValidateServlet exception : " + sqle);
}
in Logout servlet I wrote above code in doPost and doGet method. After logout it shows login screen and then if I press back button it shows previous screen before logout and then if I click on any page it shows "HTTP Status 500" and now if I press F5 then it's heating login Servlet and getting the full access of user.
How to stop this problem show that after Logout using back button and F5 user can not use any page?
What you are doing is good. Browser is caching the previous pages, and when you click back button it is taking to previous cached page.
You need to add Cache headers which does not allow browser to cache page.
Cache-Control: no-cache
1)When you are clicking on back button on browser you are getting previous page because of browser cache.
2)When you are clicking on any page after backing you are getting status 500 because there is null pointer exception because of session object is invalidate already.
3)When you refresh new request is going to your servlet or JSP, there your are calling request.getSession(); method, which is creating new session object for you.
as a result you are getting full access to all pages again.
To avoid this problem you can follow the below steps.
1)In the application create one servlet Ex:LoginCheckerServlet
2)for the above servlet give url pattern /*
3)So the servlet will be executed for all the request
4)Now in LoginCheckerServlet check for username and password in request parameters
5)If they are coming perform login checking operation and display welcome page
6)If user name password are not coming, there are two meanings
i)user is already logged in
ii)user is trying to access your app illegally
7)Now call request.getSession(false); method which will give you session object is there is session already existing for this user so you can redirect to welcome page with trust on user.
8)request.getSession(false); will give you null value if there is no session existing for this user.
9)In case if you are not getting username and password in request parameters as well as request.getSession(false); is giving you null value means user is trying to access your application without logging in, now you can happily display forbidden page.
In every servlet, check whether Session is null or not. If session is not null then only do the request processing else redirect to login page.
HttpSession session = request.getSession();
if(Session !=null)
{
try
{
// acutal servlet actions
}else
{
// redirect to login page
}
Also it would be good if you add null check for session in your above code.
HttpSession session = request.getSession();
if(session !=null)
try
{
session.removeAttribute("logonSessData");
session.invalidate();
String pageToForward = request.getContextPath();
response.sendRedirect(pageToForward); }
catch (Exception sqle)
{
System.out.println("error UserValidateServlet message : " + sqle.getMessage());
System.out.println("error UserValidateServlet exception : " + sqle);
}
}else
{
//session already null/ expired
}
What you need to do is set the session into an attribute based on the session.
request.getSession().setAttribute("sess",request.getSession());
Use this to compare it to the current session. If this comparison fails, then redirect to the login page. This should be done in each page.
This will create a new session
HttpSession ss = request.getSession(true); //creates a new session.
if(ss.isNew()){
ss.invalidate(); //this clears the session
ss = request.getSession(true); // creates a new session
}
strong textI am new, need a proper way to validate. I followed
5 line code. it doent have a httpsession but still going to appointment.jsp . why so?
I followed How to check if session exists or not?
it is giving a session. org.apache.catalina.session.StandardSessionFacade#3b59e880 but the user is not login in...
it does. but I dont know why and how it got one?
if (request.getSession(false) == null) {
request.getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
} else if (request.getSession(false) != null) {
request.getServletContext().getRequestDispatcher("/appointment.jsp").forward(request, response);
}
Session is not created after your user logs in, It is created at the first request to the container from a browser. This enables container to track subsequent requests from same browser. This is implemented usually using a cookie with unique id(session id).
So even it depends on what is happening at user logout? are you calling session.invalidate().
We cant say a user as authenticated just because session object is not null.
There will always be a HttpSession object (ok, not always, but most of the time) - this is not an indicator for an authenticated user.
You need to set a session attribute eg. "authenticated" to flag this session as authenticated or not.
You can add this by calling request.getSession().setAttribute(...)
By default, a JSP will create a session. You probably don't want that behavior for your login page, so use the page directive in login.jsp:
<%# page session="false" %>
You would also need to make sure that any other JSP that is accessed before a successful login does not create a session.
if (request.getSession(false).getAttribute("userLoggedIn") != null ) {
if((Boolean)request.getSession(false).getAttribute("userLoggedIn") ) {
request.getServletContext().getRequestDispatcher("/appointment.jsp").forward(request, response);
}
} else {
request.getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
}