webpage authentication in jsf - java

I'm having a problem in identifying a session timeout page and a page navigated directly...
user will first fill a form and submits it, based on the search he will land on information page. for some reason if he try to type the url of information page instead of coming through search page how can i restrict him?
i tried using an indicator varaible in session, but that is getting in conflict with session timeout.... how do i differentiate if it is session timeout or direct navigation?
could someone please shed some light on this and point me in right direction?

From my understanding your question is:
User should not be able to access a certain page say Page1.xhtml directly. He should first fill in a form on page2.xhtml and then should be directed to this page by the server itself.
Solution:
You could put the page1.xhtml inside web-inf directory of your webapp, which will restrict direct access to your webpage.
You could you use securityConstraint tag of the web.xml and make use of container security to restrict direct access.

You could test for a server side session timeout as follows:
if (request.getRequestedSessionId() != null && !request.isRequestedSessionIdValid()) {
// The session has been timed out (or a hacker supplied a fake cookie).
}
The request is here the HttpServletRequest which you can obtain in the JSF context from the ExternalContext#getRequest() or, actually better, inside a Filter by just downcasting the ServletRequest argument.
As a completely different alternative, you could also introduce a timed ajax poll as a "heartbeat" so that the session never expires as long as the user has the page open in the browser.

Related

Securely passing parameters in JSP/Servlet (No Frameworks)

We have a JSP page and a Servlet page, where we pass the parameters via URL from JSP to Servlet. Below is the JSP link
Allergies
In our servlet, we do some process like below.
int id = Integer.parseInt(request.getParameter("idClient"));
//Do the work
RequestDispatcher d = request.getRequestDispatcher("view.jsp");
d.forward(request,response);
Unfortunately this makes the idClient 100% visible and it is also editable. We have noticed that the user can simply edit the idClient from the URL and access other client information too! Not only that, any one can access anyones info, whether the client is belong to them or not!
How can we stop this?
Get the logged-in user.
Check whether that user is supposed to be able to access this client's details.
If not, return an error page instead of the client details page.
I can't be more specific without knowing the details of your existing code and database structure.

spring mvc tracing the referrer page

In annotation based spring controller. if a user was on url.com/first/page and clicked a link or submitted a form pointing to say url.com/second/page .
How to make the second/page know the url of /first/page so that the second/page can
1) redirect the user to the first/page again when the form values are processed.
2) or show a back button link to the /first/page?
Edit 1 --
request.getHeader('Referer') is another but those I think are browser based on the mercy of browser. If the browser dont do it, we cant know. I wanted a way which is application wide. some how passing the url from one page to another
Edit 1 end --
you can use two below methods:
request.getAttribute("javax.servlet.forward.request_uri")
or
request.getHeader("Referer");
In above methods you are trusting the browser behavior and also the container which make the request object available to you. I don't know why you don't want to use this method.
Or
you can get the current page/serlvet url save it in the session and use it in the second page.
String requestUrl=request.getRequestURL();
session.setAttribute("pervious_page",requestUrl);
Then in the second page:
session.getAttribute("pervious_page");

Spring MVC strange behavior

I have a method that handles request with a URI of "/home". This request is generated upon successful log-in procedure. Here is a little code to support my situation:
<security:form-login login-processing-url="/static/j_spring_security_check"
login-page="/login" authentication-failure-url="/login?login_error=t"
default-target-url="/home"/>
The method body demonstrates what I am attempting to achieve:
String userMail = SecurityContextHolder.getContext().
getAuthentication().getName();
logger.info(userMail);
Person p = userService.retrieveUserByEmail(userMail);
session.setAttribute("person", p);
return "user/home";
This bit is important as the person p is used as data source for other requests.
Now the problem. I don't know if it is the property of Google Chrome, but for some reason the browser remembers the request you've done before log-in and instead of going through /home request after successful log-in procedure, it generates the previous request bypassing this /home gate, resulting in null pointer exception as person p was never set up, as session wasn't populated by /home request.
I know that for other requests I should do validation, but I don't like the idea of letting user generate any request without prior going through /home .
Done with text description and now to explain how I get unwanted behaviour in steps:
ask for request that you know exist such as:
myApp/nameOfSomething/viewThisSomething - you are brought to log-in page as expected(you must be authenticated for request to be accepted)
you enter correct credentials and instead of going to default-target-url="/home"
you are automatically making previous request myApp/nameOfSomething/viewThisSomething without populating session with necessary data and resulting in nullpointer exception.
What else is interesting is that logger shows the mail, so it might be that they are both executed at the same time but /home request is slower - can that happen?
I resolve the situation in other method by checking if null and forcing to go back to /home which works as expected, but I am control freak and don't like when user is doing what he is not intended to do.
Thank You for Your time,
It's not a bug, it's a feature. It's much more user-friendly to let the user go where he wants to go after login than forcing him to go to the home page. He could have bookmarked one of the protected pages, or simply browsed some non-protected pages containing a link to a protected page.
From http://static.springsource.org/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#ns-form-target:
If a form login isn't prompted by an attempt to access a protected
resource, the default-target-url option comes into play. This is the
URL the user will be taken to after successfully logging in, and
defaults to "/". You can also configure things so that the user always
ends up at this page (regardless of whether the login was "on-demand"
or they explicitly chose to log in) by setting the
always-use-default-target attribute to "true"
IMHO, you should keep things as is, but make sure that the required sesion attribute is set once the login is successful, instead of setting this attribute in the home page. This would ensure that every protected page has access to the session attribute, even if the user didn't go to the home page.
You could do this easily by using a custom UsernamePasswordAuthenticationFilter subclass, that sets the appropriate attribute in session once the authentication has succeeded.

Java: Session attribute is only in next operation

I'm posting some strings in my Session with the call
request.getSession().setAttribute(key, value);
And making the redirect with
response.sendRedirect(urlRedirect);
In almost all cases the values is there after the redirect.
But sometimes I can only read this value in the next page view, not in the redirect. There is no common behavior.
Someone has faced the same problem?
Sessions are backed by a HTTP cookie. On first-time session creation, a cookie will be set in the response header. By default, cookies are bound to a specific context only.
So, if you redirect while the cookie hasn't been set yet, the session will get lost. To go around this, you need to encode the redirect URL.
response.sendRedirect(response.encodeRedirectURL(url));
This appends the jsessionid identifier to the URL which allows the servletcontainer to locate the right session without help of a cookie.
If you don't like the jsessionid thing, then consider implementing a filter like this which ensures that the client is aware of the session cookie before the request enters your controller wherein you fire the redirect.
Also, if you redirect to a different context, it won't be able to access the same session. To go around this, you need to configure the servletcontainer to share the session among the contexts. In for example Tomcat, check the emptySessionPath attribute of the <Connector> element in /conf/server.xml.
Such a behaviour can be caused by caching.
If the page you are redirecting to is retrieved from the browser cache, you obviously can't see the result of setAttribute() on it. So make sure it's actually requested by the browser.
Are you sure you need to do redirect through browser (response.sendRedirect()) and not on the server side (RequestDispatcher.forward())? Latter is faster as there are no network round trip.
The problem was solve by changing the way of submit.
The page was submitting the data only changing the value of location.href to the Servlet Action.
We only call the submit function from the page form, and the session attributes works fine!

Manage Session when broswer has disable cookies

I wants to know that How can i Manage Session if the client browser has disabled cookie feature..
If I wants to implement it in simple JSP - Servlet, then how can I do that ?
Thanks in advance...
Without cookies, you have two options. The first is passing a sessionId through Urls. This requires a lot of work on the server because every url you send back must have a sessionId appended to it (usually in the form of a query string parameter). For example:
/path/to/page
becomes
/path/to/page?sessionid=ASDFG-ASDFG-ASDFG-ASDFG-ASDFG
The other option you have would be to combine what information you have via http into a "unique" key and create your own session bucket. By combining the Http UserAgent, RemoteIp and RemoteXfip you can get close to uniquely identifying a user, but there is no guarantees that this key is 100% unique.
In the JSP side, you can use JSTL's <c:url> for this.
link
Easy as that. It will automagically append the jsessionid when cookies are disabled.
In the Servlet side you need HttpServletResponse#encodeURL() or -usually the preferred one inside Servlets- HttpServletResponse#encodeRedirectURL() for this.
response.sendRedirect(response.encodeRedirectURL("page.jsp"));
url rewriting
http://www.developertutorials.com/tutorials/java/implement-session-tracking-050611/page5.html
Each URL must be encoded using response.encodeURL("page.jsp")
This will add the Session ID onto the end of each URL so cookies do not have to be enabled.
Note that you will have to do this manually for every single URL in order for it to work.
See this link for more info.

Categories