Spring Security exclude URL in timeout - spring

In Spring Security, how to exclude one particular URL from resetting the session timeout? Overall application session timeout(server.servlet.session.timeout) is 15 minutes. We have a ajax call from the web page that will get called every 1 minute. This call needs to be secured, but should not impact the session time.
We have tried adding a filter extending ConcurrentSessionFilter. Also, a filter extending SessionManagementFilter. Adding ignoring() skips authentication too. Nothing helped. Can this requirement be achieved in Spring Security? Any suggestions?

This is how i handled it. Just sharing, it may be of help to someone. Please share any better ways.
Spring Security filter is added as last in the chain.
http.addFilterAfter(new SessionInvalidationFilter(timeOutInMinutes), SwitchUserFilter.class);
It keeps track of a lastUpdatedTime, which gets updated for all calls except for those URLs that needs to be ignored. In case, the differential time is greater than the configured timeout, session gets invalidated.
public class SessionInvalidationFilter extends GenericFilterBean {
private static final String LASTUPDATEDDATETIME = "LASTUPDATEDDATETIME";
private static final List<String> ignoredURLs = Arrays.asList("/Notifications/number"); // this is the AJAX URL
private int timeOutInMinutes = 15;
public SessionInvalidationFilter(int timeOutInMinutes) {
this.timeOutInMinutes = timeOutInMinutes;
}
#Override
/**
* LASTUPDATEDDATETIME is updated for all calls except the ignoredURLs.
* Session invalidation happens only during the ignoredURLs calls.
*/
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
try {
if (session != null && request.getRequestURI() != null) {
if (ignoredURLs.contains(request.getRequestURI())) {
Object lastUpdatedDateTimeObject = session.getAttribute(LASTUPDATEDDATETIME);
if (lastUpdatedDateTimeObject != null) {
LocalDateTime lastUpdatedDateTime = (LocalDateTime) lastUpdatedDateTimeObject;
long timeInMinutes = ChronoUnit.MINUTES.between(lastUpdatedDateTime, LocalDateTime.now());
if (timeInMinutes >= timeOutInMinutes) {
log.info("Timing out sessionID:{}", session.getId());
session.invalidate();
SecurityContextHolder.clearContext();
}
}
} else {
session.setAttribute(LASTUPDATEDDATETIME, LocalDateTime.now());
}
}
} catch (Exception e) {
log.error("Exception in SessionInvalidationFilter", e);
}
chain.doFilter(request, response);
}
}

Related

HttpServletRequest getting new session

I have an application that does authentication via oauth.
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpReq = (HttpServletRequest) request;
HttpServletResponse httpResp = (HttpServletResponse) response;
// Check if already logged in
if (getUser(httpReq) != null) {
chain.doFilter(request, response);
return;
}
// Try to parse auth response
if (procAuthResponse(httpReq)) {
chain.doFilter(request, response);
return;
}
// Go to auth server
sendAuthRequest(httpReq, httpResp);
}
This works fine.
In the method procAuthResponse I am paring the response from the server and to this.
HttpSession session = request.getSession();
session.setAttribute(USER_PRINCIPLE_ATR, userInfo);
It works also well, but there is a session scoped class with the method getCurrent user, that is used by servlets.
public UserInfo getCurrentUser() {
HttpSession session = getHttpSession();
if (session == null) {
LOG.warn("Method getCurrentUser: unable to find a session");
return null;
}
Object user = session.getAttribute(OAuthLoginFilter.USER_PRINCIPLE_ATR);
if (!(user instanceof UserInfo)) {
LOG.warn(String.format("Method getCurrentUser, wrong type for attribute %s", OAuthLoginFilter.USER_PRINCIPLE_ATR));
return null;
}
currentUser = (UserInfo) user;
return currentUser;
}
This method gets called multiple times and it turnes out that on the first call everything works as expected and after that the getHttpSession() returns a different session that does not contain any information that is set in the filter class. It is not a new session every time, the session without the needed information is always the same.
Code of getHttpSession()
private HttpSession getHttpSession() {
Object request = FacesContext.getCurrentInstance().getExternalContext().getRequest();
if (!(request instanceof HttpServletRequest)) {
LOG.warn("not a valid http request");
return null;
}
HttpServletRequest hreq = (HttpServletRequest) request;
return hreq.getSession(false);
}
Do you have any idea why this happens?
Thx for your help
There was still an old filter class, not configured in the web.xml, but annotated with #WebFilter("/*").
I deleted this file and now everything works as expected.

servlet Filter is not allowing to load application resources

I am trying to prevent CSRF(Cross site request forgery). To prevent CSRF I have created filter which will filter every request.
After implementing the javax.servlet.Filter as expected filter does its job. But after implementing servlet filter my application resources are not loading properly.
CSS, jQuery, datatable, all the resources are not loading properly, some time they are loading, some time not.
Before implementing the filter it was working fine.
Sample error in firebug:
"NetworkError: 500 Internal Server Error - http://localhost:8080/myApp/resources/images/bg-report-content.jpg"
"NetworkError: 500 Internal Server Error - http://localhost:8080/myApp/resources/images/bg-header.jpg"
tworkError: 500 Internal Server Error - http://localhost:8080/myApp/resources/css/dataTables.bootstrap.css"
"NetworkError: 500 Internal Server Error - http://localhost:8080/myApp/resources/js/fnStandingRedraw.js"
"NetworkError: 500 Internal Server Error - http://localhost:8080/myApp/resources/js/dataTables.tableTools.js"
This How I implemented the Filter for CSRF
What I am doing is , I have created a class called LoadSalt whic creates the salt(random number). that random number I am taking in jsp. and along with the jsp I am sending it with the request.
LoadSalt calss
public class LoadSalt implements Filter{
public Cache<String, Boolean> csrfPreventionSaltCache= null;
HttpServletRequest httpReq=null;
//int count=0;
#SuppressWarnings("unchecked")
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
//count++;
// Assume its HTTP
httpReq = (HttpServletRequest)request;
if(httpReq.getAttribute("csrfPreventionSaltCache")!=null)
{
csrfPreventionSaltCache= (Cache<String, Boolean>) httpReq.getAttribute("csrfPreventionSaltCache");
}
if(csrfPreventionSaltCache == null)
{
// creating a new cache
csrfPreventionSaltCache = CacheBuilder.newBuilder().maximumSize(5000)
.expireAfterAccess(5, TimeUnit.MINUTES).build();
// Setting to httpReq
httpReq.setAttribute("csrfPreventionSaltCache", csrfPreventionSaltCache);
}
// Generate the salt and store it in the users cache
String salt = RandomStringUtils.random(20, 0, 0, true, true, null, new SecureRandom());
//System.out.println("Salt: "+salt);
csrfPreventionSaltCache.put(salt, Boolean.TRUE);
// Add the salt to the current request so it can be used
// by the page rendered in this request
httpReq.setAttribute("csrfPreventionSalt", salt);
chain.doFilter(httpReq, response);
}
public void init(FilterConfig arg0) throws ServletException {
}
public void destroy() {
}
}
The another filter which validate the salt
public class ValidateSalt implements Filter {
public Cache<String, Boolean> csrfPreventionSaltCache= null;
#SuppressWarnings("unchecked")
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// Assume its HTTP
HttpServletRequest httpReq = (HttpServletRequest) request;
HttpServletResponse httpResponse =(HttpServletResponse) response;
String salt =(String) httpReq.getAttribute("csrfPreventionSalt");
// Validate that the salt is in the cache
if(httpReq.getAttribute("csrfPreventionSaltCache")!=null)
{
csrfPreventionSaltCache = (Cache<String, Boolean>) httpReq.getAttribute("csrfPreventionSaltCache");
}
if(csrfPreventionSaltCache !=null && salt !=null && csrfPreventionSaltCache.getIfPresent(salt)!=null)
{
String metodName =httpReq.getMethod();
String saltFromJspPage = httpReq.getParameter("salt");
//String saltFromRequest =(String) httpReq.getAttribute("csrfPreventionSalt");
if(metodName.equalsIgnoreCase("POST"))
{
if(saltFromJspPage!=null && csrfPreventionSaltCache.getIfPresent(saltFromJspPage)!=null)
{
chain.doFilter(httpReq, response);
else
{
//throw new ServletException("Potential CSRF detected!! Please contact to system admin ASAP.");
httpResponse.sendRedirect("/myApp/pages/pageNotFound.jsp");
}
}
else
{
chain.doFilter(httpReq, response);
}
}
else
{
// Otherwise we throw an exception aborting the request flow
//throw new ServletException("Potential CSRF detected!! Inform a scary sysadmin ASAP.");
httpResponse.sendRedirect("/myApp/pages/pageNotFound.jsp");
}
}
public void init(FilterConfig arg0) throws ServletException {
}
public void destroy() {
}
}
servlet filter mapping in web.xml
<filter>
<filter-name>loadSalt</filter-name>
<filter-class>com.mpApp.security.LoadSalt</filter-class>
</filter>
<filter-mapping>
<filter-name>loadSalt</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>validateSalt</filter-name>
<filter-class>com.mpApp.security.ValidateSalt</filter-class>
</filter>
<filter-mapping>
<filter-name>validateSalt</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
What is wrong with my application?
Why servlet filter is not allowing to load resources?, though some time it does work , some time it does not,
What is the route cause of this?
Am I implementing servlet filter in wrong way.
please help.
The url pattern is too wide, will try to apply the salt to every request. Keep it to the dynamic parts you can set and check the salt value, like /transferOperationServlet or /prettyImportantServlet or *.jsp

How to set, get and validate sessions in JSF like PHP $_SESSION[''] [duplicate]

I would like to block the access of some page even if the user knows the url of some pages.
For example, /localhost:8080/user/home.xhtml (need to do the login first) if not logged then redirect to /index.xhtml.
How do that in JSF ? I read in the Google that's needed a filter, but I don't know how to do that.
You need to implement the javax.servlet.Filter class, do the desired job in doFilter() method and map it on an URL pattern covering the restricted pages, /user/* maybe? Inside the doFilter() you should check the presence of the logged-in user in the session somehow. Further you also need to take JSF ajax and resource requests into account. JSF ajax requests require a special XML response to let JavaScript perform a redirect. JSF resource requests need to be skipped otherwise your login page won't have any CSS/JS/images anymore.
Assuming that you've a /login.xhtml page which stores the logged-in user in a JSF managed bean via externalContext.getSessionMap().put("user", user), then you could get it via session.getAttribute("user") the usual way like below:
#WebFilter("/user/*")
public class AuthorizationFilter implements Filter {
private static final String AJAX_REDIRECT_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<partial-response><redirect url=\"%s\"></redirect></partial-response>";
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
String loginURL = request.getContextPath() + "/login.xhtml";
boolean loggedIn = (session != null) && (session.getAttribute("user") != null);
boolean loginRequest = request.getRequestURI().equals(loginURL);
boolean resourceRequest = request.getRequestURI().startsWith(request.getContextPath() + ResourceHandler.RESOURCE_IDENTIFIER + "/");
boolean ajaxRequest = "partial/ajax".equals(request.getHeader("Faces-Request"));
if (loggedIn || loginRequest || resourceRequest) {
if (!resourceRequest) { // Prevent browser from caching restricted resources. See also https://stackoverflow.com/q/4194207/157882
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setDateHeader("Expires", 0); // Proxies.
}
chain.doFilter(request, response); // So, just continue request.
}
else if (ajaxRequest) {
response.setContentType("text/xml");
response.setCharacterEncoding("UTF-8");
response.getWriter().printf(AJAX_REDIRECT_XML, loginURL); // So, return special XML response instructing JSF ajax to send a redirect.
}
else {
response.sendRedirect(loginURL); // So, just perform standard synchronous redirect.
}
}
// You need to override init() and destroy() as well, but they can be kept empty.
}
Additionally, the filter also disabled browser cache on secured page, so the browser back button won't show up them anymore.
In case you happen to use JSF utility library OmniFaces, above code could be reduced as below:
#WebFilter("/user/*")
public class AuthorizationFilter extends HttpFilter {
#Override
public void doFilter(HttpServletRequest request, HttpServletResponse response, HttpSession session, FilterChain chain) throws ServletException, IOException {
String loginURL = request.getContextPath() + "/login.xhtml";
boolean loggedIn = (session != null) && (session.getAttribute("user") != null);
boolean loginRequest = request.getRequestURI().equals(loginURL);
boolean resourceRequest = Servlets.isFacesResourceRequest(request);
if (loggedIn || loginRequest || resourceRequest) {
if (!resourceRequest) { // Prevent browser from caching restricted resources. See also https://stackoverflow.com/q/4194207/157882
Servlets.setNoCacheHeaders(response);
}
chain.doFilter(request, response); // So, just continue request.
}
else {
Servlets.facesRedirect(request, response, loginURL);
}
}
}
See also:
Our Servlet Filters wiki page
How to handle authentication/authorization with users in a database?
Using JSF 2.0 / Facelets, is there a way to attach a global listener to all AJAX calls?
Avoid back button on JSF web application
JSF: How control access and rights in JSF?
While it's of course legitimate to use a simple Servlet filter, there are alternatives like
Spring Security
Java EE Security
Apache Shiro

JSF ajax request calls filter (should be ignored!)

I have some filters, which grab e.g. a parameter like "id" to check some right (used to load some contents). These filters should ignore all ajax-requests, because e.g. the rights does not have to be checked after every little request (only on page load)
The Problem is, that when I perform an ajax-request, it throws me a null-pointer, because I don't append the ID with ajax requests. I found out, that it still works, when I use and it fails, when I use (both perform ajax requests).
This is my filter:
public class ExtendedAccessFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
//ignore filter if it is an ajax-request (DOES NOT WORK if not p:commandButton!)
if(isAJAXRequest(req)){
chain.doFilter(request, response);
System.out.println("ABORT FILTER, AJAX");
return;
}
//Nullpointer thrown here (because no Id is submitted)
int requestedId = Integer.parseInt(request.getParameter("id"));
}
private boolean isAJAXRequest(HttpServletRequest request) {
boolean check = false;
String facesRequest = request.getHeader("Faces-Request");
if (facesRequest != null && facesRequest.equals("partial/ajax")) {
check = true;
}
return check;
}
}
Am I doing something wrong?
You are doing it right way. You can also do it using JSF API by checking if PartialViewContext exists and it is an Ajax Request
if(FacesContext.getCurrentInstance().getPartialViewContext() !=null &&
FacesContext.getCurrentInstance().getPartialViewContext().isAjaxRequest()) {
}

How to design a session-less JSF 2.0 web application?

I am working on a JSF 2.0 website. The website has two kind of users(public and registered). Now I want to know that how can I create session for both kind of users? For registered users, when my user is login then there should be session for it, and when session expires then I redirect it to page that your session has expired. For public users there should be no session at all. Means there is no session time out for my public users and they never have messages that your session has expired. How can I implement this behavior in JSF 2.0.
Can I use filter for it or there is better approach for it? I also read that JSF automatically creates session using managed beans. Can I use these sessions for my task?
Edit:
I tell you what i did so you people better guide me in this scenerio
What i did i put a filter in my web app like this
<filter>
<filter-name>SessionTimeoutFilter</filter-name>
<filter-class>util.SessionTimeoutFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SessionTimeoutFilter</filter-name>
<url-pattern>*.xhtml</url-pattern>
</filter-mapping>
Here is my Filter code
public class SessionTimeoutFilter implements Filter {
// This should be your default Home or Login page
// "login.seam" if you use Jboss Seam otherwise "login.jsf"
// "login.xhtml" or whatever
private String timeoutPage = "faces/SessionExpire.xhtml";
private String welcomePage = "faces/index.xhtml";
public static Boolean expirePage = false;
private FilterConfig fc;
#Override
public void init(FilterConfig filterConfig) throws ServletException {
this.fc = filterConfig;
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
HttpSession session = httpServletRequest.getSession();
/**
* The session objects have a built-in data structure (a hash table) in which you can store
* any number of keys and associated values. You use session.getAttribute("key") to look up
* a previously stored value. The return type is Object, so you must do a typecast to
* whatever more specific type of data was associated with that attribute name in the session.
* The return value is null if there is no such attribute, so you need to check for null
* before calling methods on objects associated with sessions.
*
* Note:
* JSF session scoped managed beans are under the covers stored as a HttpSession
* attribute with the managed bean name as key.
*/
Login login = (Login)session.getAttribute("login");
if (login == null) { // No such object already in session
filterChain.doFilter(request, response);
} else {
/**
* If you use a RequestDispatcher, the target servlet/JSP receives the same
* request/response objects as the original servlet/JSP. Therefore, you can pass
* data between them using request.setAttribute(). With a sendRedirect(), it is a
* new request from the client, and the only way to pass data is through the session or
* with web parameters (url?name=value).
*/
filterChain.doFilter(request, response);
}
System.out.println();
} //end of doFilter()
#Override
public void destroy() {
} //end of destroy()
Now what happen that if you first time enter url of my site then this filter invoke. It gets
Login login = (Login)session.getAttribute("login");
null. So it simply move to my index.xhtml page. Now my index.html page constructor invokes. Here is my code
#ManagedBean
//////#RequestScoped
#SessionScoped
public class Login implements Serializable {
//Constructor
public Login() {
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
//getSession(false), which returns null if no session already exists for the current client.
HttpSession session =(HttpSession)externalContext.getSession(false);
if (session == null) {
System.out.println();
} else {
session.setAttribute("logedin", 0); //public user
session.setMaxInactiveInterval(-1); // no session time out
Enumeration e = session.getAttributeNames();
while (e.hasMoreElements()) {
/**
* Here you also get "login" attr. Because when managed bean create the
* session, it sets you managedBean name in the session attribute.
*/
String attr = (String)e.nextElement();
System.err.println("attr = "+ attr);
Object value = session.getAttribute(attr);
System.err.println("value = "+ value);
} //end of while
}
}//end of constructor
} //end of class Login
when first time user come to my site then it is not login so i set logedin session attribute 0. Now suppose user enter credentials and press log in button. First my filter is invoke but this time it will get login attribute and comes to my doFilter() else check and then come to My validUser() method. Here is my code
public String validUser() throws Exception {
ArrayList2d<Object> mainarray = new ArrayList2d<Object>();
mainarray.addRow();
mainarray.add(userName);
mainarray.add(password);
busBeans.usermanagement.users um = new busBeans.usermanagement.users();
ArrayList retrieveList = um.getValidUser(mainarray); //database check of user existence
if (Integer.parseInt(retrieveList.get(0).toString()) == 0) {
ArrayList str = (ArrayList) retrieveList.get(1);
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
//getSession(false), which returns null if no session already exists for the current client.
HttpSession session =(HttpSession)externalContext.getSession(false);
if (session == null) {
System.out.println();
} else {
Enumeration e = session.getAttributeNames();
while (e.hasMoreElements()) {
String attr = (String)e.nextElement();
System.err.println("attr = "+ attr);
Object value = session.getAttribute(attr);
System.err.println("value = "+ value);
} //end of while
}
logedin=true;
session.setAttribute("logedin", 1);
session.setAttribute("firstLastName", str.get(7).toString());
session.setAttribute("getusercredentials", str);
session.setAttribute("sessionUserId", str.get(0).toString());
session.setAttribute("sessionRoleId",str.get(1).toString());
firstLastName = session.getAttribute("firstLastName").toString();
session.setMaxInactiveInterval(60); //1 min
ConnectionUtil.setRgihts(Integer.parseInt(str.get(0).toString()) , Integer.parseInt(str.get(1).toString()) ,Integer.parseInt(str.get(5).toString()));
checkRgihts();
}
} //end of validUser()
Now i want to ask one thing. I set sessionTimeout using setMaxInterval. Is it ok or it is better to do in web.xml? Now whne timeOut expires then filter doesn't invoke. But suppose that I also attach HttpSessionListener. Then on session time Out its destroy method invoke. I can invalidate session here. Like this.
public class MySessionListener implements HttpSessionListener {
// Constructor
public MySessionListener() {
} //end of constructor
#Override
public void sessionCreated(HttpSessionEvent event) {
System.out.println("Current Session created : " + event.getSession().getCreationTime());
System.out.println();
} //end of sessionCreated()
#Override
public void sessionDestroyed(HttpSessionEvent event) {
// get the destroying session...
HttpSession session = event.getSession();
if (session != null) {
session.invalidate();
}
System.out.println();
} //end of sessionDestroyed()
} //end of class MySessionListener
But on session expiration i also want to redirect user to redirecr Page if this is a registered user. IF this is a public user i don't want to redirect it although session has expired. I can check in the destroy method by getting attribute logedin that it is a public user or registered user. But then how can i redirect for registered user or do nothing for public user.
If somehow my filter invoke on session time out and some how i check that if this is a registered user by getting logedin attribute 1 and session time out has expired, because for public user i set timeout -1, then redirect the user, using RequestDispatcher otherwoise do filterChain.doFilter(request, response);.
So this is the scenerio that i implemented. I don't know whether my approaches are right or not ? I don't know what security issues i will face by this approach. So that's it.. Now you people guide me what should i do.....
Thanks
I understand what your goal is, but I don't think that not having a Session for unauthenticated users is particularly the best approach.
Consider an unauthenticated user navigating through a Primefaces wizard as he provides information to sign up for an account, (Eg. Pick Username, Provide Password, Choose Security Questions, etc...)
You are not going to want to persist this user information until it all has been collected and validated, because perhaps the user has a change of heart and decides not to sign up? Now you have an incomplete user record in your database that needs to be cleaned.
The answer is that you need to store this information in a ViewScoped bean or in session until the unauthenticated user confirms the account creation, where it can finally be persisted.
What I feel the best approach would be is for you to give a User a unique Role with one role being Unauthenticated. Using components like Spring Security 3 or even Seam you should be able to control page Authorization through the Role of the User in Session.
For instance, you can prevent unauthenticated users from entering pages in ../app/* or normal users from accessing pages in ../admin/*
I used some thing like this. First there is a filter. Here is my filter
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
//Send request to server after each 1min
// httpServletResponse.setIntHeader("Refresh", 60);
//getSession(false), which returns null if no session already exists for the current client
HttpSession session = httpServletRequest.getSession(false);
if (session == null) {
//session timeout check.
if (httpServletRequest.getRequestedSessionId() != null && !httpServletRequest.isRequestedSessionIdValid()) {
System.out.println("Session has expired");
/**
* getSession() (or, equivalently, getSession(true)) creates a new session if no
* session already exists.
*/
session = httpServletRequest.getSession(true);
session.setAttribute("logedin", "0"); // public user
//httpServletResponse.sendRedirect("http://www.google.com");
httpServletResponse.sendRedirect(timeoutPage);
} else {
session = httpServletRequest.getSession(true);
session.setAttribute("logedin", "0");
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
} else {
String isRegisteredUser = session.getAttribute("logedin").toString();
if (isRegisteredUser.equalsIgnoreCase(("1"))) {
Login login = (Login)session.getAttribute("login");
Enumeration e = session.getAttributeNames();
System.out.println("");
filterChain.doFilter(httpServletRequest, httpServletResponse);
} else if (isRegisteredUser.equalsIgnoreCase(("0"))) {
Enumeration e = session.getAttributeNames();
filterChain.doFilter(httpServletRequest, httpServletResponse);
} //end of else if (isRegisteredUser.equalsIgnoreCase(("0")))
}
} //end of doFilter()
Now when user enter url of my site then this filter invoke. First time it get session null then it checks for session timeout. no session time out so it creates a session. Set logedin attribute to zero, means this is public user and pass the request. Here is my method
//constructor
public Login() {
try {
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
HttpServletRequest httpServletRequest = (HttpServletRequest)externalContext.getRequest();
//getSession(false), which returns null if no session already exists for the current client.
HttpSession session =(HttpSession)externalContext.getSession(false);
if (session == null) {
session = httpServletRequest.getSession(true);
session.setAttribute("logedin", "0");
session.setMaxInactiveInterval(-1);
System.out.println();
} else {
session.setAttribute("logedin", "0");
//No session timeout for public users
session.setMaxInactiveInterval(-1);
Enumeration e = session.getAttributeNames();
}
} catch (Exception e) {
System.out.println("Exception in session " + e.getMessage());
}
} //end of constructor
First time it gets session, just override the values so there is no harm to set the same attribute. But here i just want to ask one thing that is it ok to set no session time out for public users ? will it damage my application at some point, like my server goes out of memory and etc ? If yes, then how can i overcome this ?
Now suppose that my user is log in. Then my filter invoke, this time it will get a session so it comes to my isRegisterdUser check and check the value. He get 0 , just pass the request and then my valid user method call.
public String validUser() throws Exception {
String returnString = null;
ArrayList2d<Object> mainarray = new ArrayList2d<Object>();
mainarray.addRow();
mainarray.add(userName);
mainarray.add(password);
busBeans.usermanagement.users um = new busBeans.usermanagement.users();
ArrayList retrieveList = um.getValidUser(mainarray);
if (Integer.parseInt(retrieveList.get(0).toString()) == 0) {
ArrayList str = (ArrayList) retrieveList.get(1);
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
//getSession(false), which returns null if no session already exists for the current client.
HttpSession session =(HttpSession)externalContext.getSession(false);
if (session == null) {
System.out.println();
} else {
Enumeration e = session.getAttributeNames();
}
System.out.println();
logedin=true;
//Set session attributes for login users
session.setAttribute("logedin", 1);
session.setAttribute("firstLastName", str.get(7).toString());
session.setAttribute("getusercredentials", str);
session.setAttribute("sessionUserId", str.get(0).toString());
session.setAttribute("sessionRoleId",str.get(1).toString());
session.setAttribute("registeredUser", "true");
/**
* set session timeout for login user
* 1 min = 60 sec
* 5 min = 60 * 5 sec = 300 sec
*/
session.setMaxInactiveInterval(300); //5min
firstLastName = session.getAttribute("firstLastName").toString();
}
return returnString=null;
} //end of validUser()
I override the value of logedin attribute to 1 so now the user become valid user. Now if valid user make request then my filter invoke, it will get a session so it comes to my isRegisterdUser check, this time it get value 1 so just pass the request.Now when session time out and user make any request, then my filter invoke and this time it comes inside the check
if (httpServletRequest.getRequestedSessionId() != null && !httpServletRequest.isRequestedSessionIdValid()) {
System.out.println("Session has expired");
//httpServletResponse.sendRedirect("http://www.google.com");
httpServletResponse.sendRedirect(timeoutPage);
} else {
session = httpServletRequest.getSession(true);
session.setAttribute("logedin", "0");
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
and redirect the user by making it public. So here how this i do it. I got also a idea that i refresh the page after some time, i have sessionCreationTime, sessionLastAccessTime and sessionMaxTime. so i can do a work like this
String isRegisteredUser = session.getAttribute("logedin").toString();
if (isRegisteredUser.equalsIgnoreCase(("1"))) {
Login login = (Login)session.getAttribute("login");
Enumeration e = session.getAttributeNames();
while (e.hasMoreElements()) {
String attr = (String)e.nextElement();
System.err.println("attr = "+ attr);
Object value = session.getAttribute(attr);
System.err.println("value = "+ value);
} //end of while
long sessionCreationTime = session.getCreationTime();
int sessionCreationTimeInSec = (int)(sessionCreationTime / 1000) % 60;
int sessionCreationTimeInMinutes = (int)((sessionCreationTime / (1000*60)) % 60);
long sessionLastAccessTime = session.getLastAccessedTime();
int sessionLastAccessTimeInSec = (int)(sessionLastAccessTime / 1000) % 60 ;
int sessionLastAccessTimeInMinutes = (int)((sessionLastAccessTime / (1000*60)) % 60 );
int sessionMaxTime = session.getMaxInactiveInterval();
int sessionMaxTimeInMinute = sessionMaxTime / 60 ;
if ((sessionCreationTimeInMinutes - sessionLastAccessTimeInMinutes) - 1 > sessionMaxTimeInMinute) {
System.out.println("Session is expiring in one minute");
}
System.out.println("");
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
The idea here is that if some how you check that how much time left for session timeout then you can invalidate the session just before your session time out time. Because once your session expire you get session null and you have no attributes to check. But before one minute you have session and all session attributes so you can do whatever you want. I don't know how solid idea is this, it's just an approach that came to my mind.
Also suppose user is login and then suddenly closed the browser. Closing browser close the session. Now when you open your browser then you get a message that your session has expire. I want to ask when you open a browser can i use this check
if (httpServletRequest.getRequestedSessionId() != null && !httpServletRequest.isRequestedSessionIdValid()) {
System.out.println("Session has expired");
if (session.isNew()) {
/**
* getSession() (or, equivalently, getSession(true)) creates a new session if no
* session already exists.
*/
session = httpServletRequest.getSession(true);
session.setAttribute("logedin", "0"); // public user
filterChain.doFilter(httpServletRequest, httpServletResponse);
} else {
httpServletResponse.sendRedirect("http://www.google.com");
}
}
I used isNew() check because i want to do that if user is entering your site first time, like open his browser, then he didn't see the redirection message although his session has been expired because of closing browser.
Thanks

Resources