Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Create User Defined Session in Java

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 868
    Comment on it

    User Defined Session ID: As we know that the session is used to check the user's state. Almost every web application handles the user session. Their are number of ways to maintain the session like using url rewriting, hidden fields, cookies, web server internal session facility etc. Mostly we used web server's internal session which handles the session automatically and is very secure.

    But some of the project requires more secure session id's and need to generate their own session id and maintain it. Or someone can have requirement like use encrypted session id, so for all those requirements we need to create session id using code and maintain it throughout the user is active.

    Example of user defined session id : So following is the sample example where we are generating the session id using code.

    SessionManagementRequestWrapper.java

    package org.ecommerce.filter;
    
    import java.security.SecureRandom;
    import java.util.HashMap;
    import java.util.Map;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletRequestWrapper;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import org.apache.commons.codec.binary.Base64;
    
    public class SessionManagementRequestWrapper extends HttpServletRequestWrapper {
    
        private static final String TOKEN_KEY = "appSession";
        private static final Map<String, HttpSession> SESSIONS = new HashMap<String, HttpSession>();
        private static final SecureRandom GENERATOR = new SecureRandom();   
        private HttpServletRequest request;
        private HttpServletResponse response;
    
        /**
         * Wrapping constructor
         * @param request
         */
        public SessionManagementRequestWrapper(HttpServletRequest request, HttpServletResponse response) {
            super(request);
            this.request = request;
            this.response = response;
        }
    
        @Override
        public HttpSession getSession() {
            return this.getSession(true);
        }
    
        @Override
        public HttpSession getSession(boolean create) {
            String token = getSessionId();
            if (token == null && !create) return null;
    
            if (token==null || !SESSIONS.containsKey(token)) {
                return newSession();
            }       
            return SESSIONS.get(token);
        }
    
        private HttpSession newSession() {
            HttpSession session = super.getSession(true);
            String token =  generateSessionToken();
            response.addCookie(new Cookie(TOKEN_KEY, session.getId()));
            SESSIONS.put(token, session);
            return session;
        }
    
        private String generateSessionToken() {
            byte[] token = new byte[32];
            GENERATOR.nextBytes(token);
            return Base64.encodeBase64String(token);
        }
    
        private String getSessionId() {
            Cookie[] cookies = request.getCookies();
            for (Cookie cookie : cookies) {
                if (TOKEN_KEY.equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
            return null;
        }
    }
    

    SessionManagementWebFilter.java

    package org.ecommerce.filter;
    
    import java.io.IOException;
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.annotation.WebFilter;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    @WebFilter("/*")
    public class SessionManagementWebFilter implements Filter {
    
        @Override
        public void doFilter(ServletRequest _request, ServletResponse _response, FilterChain chain) throws IOException, ServletException {
            HttpServletRequest request = (HttpServletRequest)_request;
            HttpServletResponse response = (HttpServletResponse)_response;
            HttpServletRequest wrapper = new SessionManagementRequestWrapper(request, response);
            chain.doFilter(wrapper, _response);
        }
    
        @Override
        public void init(FilterConfig arg0) throws ServletException { }
    
        @Override
        public void destroy() { }
    }
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: