httpsession verification if exists - java

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);
}

Related

session is retriveing values of older session in jsp scriptlets

1) When user logs into our system via SSO, we generate a random token and keep that in session at server side code looks like, so it will be generated only once just after user logs in
if(slingRequest.getSession().getAttribute("csrfToken") == null){
UUID uuidRandom = UUID.randomUUID();
String Guid = "_" + uuidRandom.toString();
log.info("Random CSRF number Generated is "+Guid);
slingRequest.getSession().setAttribute("csrfToken",Guid);
}
2) On every page , we are reading from session and keeping this value in a hidden field code looks like
<%String csrfToken="";
if(null != request.getSession() && null != request.getSession().getAttribute("csrfToken")){
csrfToken=(String)request.getSession().getAttribute("csrfToken");
pageContext.setAttribute("csrfToken",csrfToken);
}
%>
<input type="text" id="csrfToken" value="${csrfToken}" style="display:none;" name="csrfToken">
3) On every POST request we are sending this csrfToken which is stored in hidden field to server and validate it at backend with the values retrieved from session at server side, if it’s is same then request is valid otherwise it’s not.
if(csrfToken.equals(request.getSession().getAttribute("csrfToken").toString() ))
4) On logout we invalidate the session and remove the token from session.
request.getSession().removeAttribute("csrfToken");
request.getSession().removeAttribute("globalAccountHolder");
request.getSession().invalidate();
Issue:
Sometimes pagesource/hidden field value is shown as same as it was in previous session, which is before log out value. i.e step 2 shows older value and when step 3 gets executed the matches of token fails, but if we reload the page using Cntrl+R then hidden field value is shown correctly and works. So not able to understand if this is browser caching problem for a page??
Tried Solution: As a solution for this we have set no-cache in our response headers, but this doesn’t work .
Is there any other solution you can think of like including any meta-tag in page header, or some otherthing?
ALso this issue i am facing sometimes only not everytime

Can session variables be modified by a hacker?

I'm working on a web application with spring mvc. I put profile data about my users in a session variable.
for( AdminProfil ap : admin.getAdminProfils()){
if(ap.getProfil().getNomProfil().equals("root")){
session.setAttribute( "root", true );
}
else if(ap.getProfil().getNomProfil().equals("saisie")){
session.setAttribute( "saisie", true );
}
else if(ap.getProfil().getNomProfil().equals("controle")){
session.setAttribute( "controle", true );
}
else if(ap.getProfil().getNomProfil().equals("validation")){
session.setAttribute( "validation", true );
}
}
and in my jsp page :
<c:if test="${ sessionScope['saisie'] }">
......
</c:if>
I want to know if the session variable can be modified by one of
my users or someone else who wants to hack my web application?
If the session can be modified what other solution can I use to stop a user from changing their profile?
Is it okay to use a session variable in my case or are cookies better?
I want to know if the session variable can be modified by one of my
users or someone else who want to hack my web application ?
No, session variables cannot be modified by one of your users or someone else
However, if you're not careful, browsers can be tricked into using the wrong session cookie, and session cookies can be stolen:
Set the httpOnly flag on your session cookie
Change the user's session id after they sign in to avoid session fixation
Use HTTPS and set the secure flag on your session cookie to avoid session hijacking
Protect your site against XSS and XSRF with a WAF like modsecurity
I'd recommend using Spring Security 4 instead of rolling your own system though.
It's okey to use session variable in my case or the cookies are better
?
Yes it's okay. No cookies are not better, as cookies can be modified by a user or someone else.

Invalidate session in Logout Servlet [duplicate]

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
}

Session variable is null when accessed second time

I am new to this forum. I am designing a JSP-Servlet application and using session variables to store objects.
Problem is, when I access the session variables for second time it returns null.
Here is the flow of my app -
I have a jsp page with mulitple link buttons. When user clicks on any button a servlet is called with respective parameters. eg 1 is passed if button1 is clicked, 2 if button2 is clicked,etc.
Servlet gets an arraylist from session variable which is already created earlier and depending on requested parameter gets the data from arraylist, processes it and sends response to another jsp say jsp2.
jsp2 also has similar link buttons and should do the same task. When the same Servlet is called from jsp2 or even if the page is refreshed, the session variable is null this time.
In my web.xml file under the session-config tag I have set the timeout to -1 so that session never expires.
<session-config>
<session-timeout>-1</session-timeout>
</session-config>
In the servlet I get the session variable as-
HttpSession session = request.getSession(false);
ArrayList<String> list = new ArrayList<String>();
list = (ArrayList<String>)session.getAttribute("mylist");
When the servlet is called second time or even if the page is refreshed the list is null.
I put few lines to check if session is valid-and it prints the second time.
if(!request.isRequestedSessionIdValid()) {
System.out.println("Session is Expired !!");
}
and the session.getAttribute("mylist") returns NullPointerException.
I am sure that I have not used session.invalidate() anywhere by chance to end the session.
I dont understand what is going wrong..can someone can explain me ?
Many thanks in advance.
You would need to try with getSession(true) for the first time or getSession().
False argument will not return session if the session doesn't exist. Only for the first time you would need to supply true in to the getSession call.
HttpSession session = request.getSession(true);
According to servlet specification,
HttpSession getSession(boolean create)
Returns the current HttpSession associated with this request or, if there is no
current session and create is true, returns a new
session.
If create is false and the request has no valid HttpSession, this method
returns null.
To make sure the session is properly maintained, you must call this method before the response is committed. If the container is
using cookies to maintain session integrity and is asked to create a
new session when the response is committed, an IllegalStateException
is thrown.
Edit - Session from session id
HttpSessionContext sc=request.getSession().getSessionContext();
HttpSession session=sc.getSession(session_id);
Note- This method is deprecated now due to security reason.
Try sending the response to some other jsp page and see if you are able to access session variable from there. If yes then there is problem in your current jsp.
Certainly the session is getting expired somewhere for sure otherwise request.getSession() will definitely return the previously created session.
Set timeout to 0, not -1 if you want unlimited session time.
You need to set the attribute somewhere, before you can retrieve it:
session.setAttribute("mylist", list);

Why Isn't Session Null

I am using the following code to delivery the user to a Welcome page if they are already logged in, or back to the login page if they are not.
HttpSession session = request.getSession(false);
if(session == null){
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
}else{
//User already logged in. Send to home.
response.sendRedirect("Welcome");
}
First time around, it works fine, but if I reload the page even once it sends the user to the welcome page and inevitably sends me back a 500 error because there are elements on that page that cannot be loaded because the user log in code has not been executed.
Does a session get started automatically even if request.getSession(true) is not declared when a page is reloaded? Is there a way to prevent this?
Probably the session is being created upon forwarding to login.jsp. That's necessary because the user has to be assigned to an unauthenticated request and then authenticate it. If you want to redirect based on whether the user is logged in or not, use SessionContext's getCallerPrincipal.
For more info, check this (somewhat old, but still relevant) article
The method request.getSession(false) returns null if there is no current session. I suggest to compare a key too.
Please take a look at this threads.
Do JSPs always create a session?
How do servlets work? Instantiation, session variables and multithreading

Categories

Resources