Example usage for javax.servlet.http HttpSession invalidate

List of usage examples for javax.servlet.http HttpSession invalidate

Introduction

In this page you can find the example usage for javax.servlet.http HttpSession invalidate.

Prototype

public void invalidate();

Source Link

Document

Invalidates this session then unbinds any objects bound to it.

Usage

From source file:org.jasig.cas.client.session.SingleSignOutHandler.java

/**
 * Destroys the current HTTP session for the given CAS logout request.
 *
 * @param request HTTP request containing a CAS logout message.
 *///  w  w  w.  ja  v a2 s  .c o m
private void destroySession(final HttpServletRequest request) {
    final String logoutMessage;
    // front channel logout -> the message needs to be base64 decoded + decompressed
    if (isFrontChannelLogoutRequest(request)) {
        logoutMessage = uncompressLogoutMessage(
                CommonUtils.safeGetParameter(request, this.frontLogoutParameterName));
    } else {
        logoutMessage = CommonUtils.safeGetParameter(request, this.logoutParameterName, this.safeParameters);
    }
    logger.trace("Logout request:\n{}", logoutMessage);

    final String token = XmlUtils.getTextForElement(logoutMessage, "SessionIndex");
    if (CommonUtils.isNotBlank(token)) {
        final HttpSession session = this.sessionMappingStorage.removeSessionByMappingId(token);

        if (session != null) {
            String sessionID = session.getId();

            logger.debug("Invalidating session [{}] for token [{}]", sessionID, token);

            try {
                session.invalidate();
            } catch (final IllegalStateException e) {
                logger.debug("Error invalidating session.", e);
            }
            try {
                request.logout();
            } catch (final ServletException e) {
                logger.debug("Error performing request.logout.");
            }
        }
    }
}

From source file:org.pentaho.platform.web.http.security.HttpSessionReuseDetectionFilter.java

public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest)) {
        throw new ServletException();
    }//from  www  .  j  a va2s  . c o  m

    if (!(response instanceof HttpServletResponse)) {
        throw new ServletException();
    }

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    if (requiresAuthentication(httpRequest, httpResponse)) {
        if (HttpSessionReuseDetectionFilter.logger.isDebugEnabled()) {
            HttpSessionReuseDetectionFilter.logger.debug(
                    Messages.getInstance().getString("HttpSessionReuseDetectionFilter.DEBUG_PROCESS_AUTHN")); //$NON-NLS-1$
        }

        // TODO: this should use LogoutHandlers in latest Spring Security

        if (null != httpRequest) {
            String remoteUser = httpRequest.getRemoteUser();
            if ((null != remoteUser) && (remoteUser.length() > 0)) {
                if (HttpSessionReuseDetectionFilter.logger.isDebugEnabled()) {
                    HttpSessionReuseDetectionFilter.logger.debug(Messages.getInstance().getString(
                            "HttpSessionReuseDetectionFilter.DEBUG_USER_ALREADY_LOGGED_IN", remoteUser)); //$NON-NLS-1$
                }

                HttpSession session = httpRequest.getSession(false);
                if (null != session) {
                    if (HttpSessionReuseDetectionFilter.logger.isDebugEnabled()) {
                        HttpSessionReuseDetectionFilter.logger.debug(Messages.getInstance()
                                .getString("HttpSessionReuseDetectionFilter.DEBUG_INVALIDATING_SESSION")); //$NON-NLS-1$
                    }
                    session.invalidate();
                }

                SecurityContextHolder.clearContext();

                if (HttpSessionReuseDetectionFilter.logger.isDebugEnabled()) {
                    HttpSessionReuseDetectionFilter.logger.debug(Messages.getInstance().getString(
                            "HttpSessionReuseDetectionFilter.DEBUG_REDIRECTING", sessionReuseDetectedUrl)); //$NON-NLS-1$
                }

                httpResponse.sendRedirect(
                        httpResponse.encodeRedirectURL(httpRequest.getContextPath() + sessionReuseDetectedUrl));
                return;
            }
        }
    }
    chain.doFilter(request, response);
}

From source file:fi.hoski.web.auth.LoginServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setCharacterEncoding("UTF-8");

    response.setHeader("Cache-Control", "private, max-age=0, no-cache");
    String action = request.getParameter("action");
    try {/*  w  w w .jav  a  2s  .  c om*/
        if (action == null || action.equals("login")) {
            // login

            String email = request.getParameter("email");
            String password = request.getParameter("password");
            email = (email != null) ? email.trim() : null;

            // 1. check params
            if (email == null || email.isEmpty() || password == null || password.isEmpty()) {
                log("email or password not ok");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
            } else {
                // 2. check user exists
                Map<String, Object> user = userDirectory.authenticateUser(email, password);
                if (user == null) {
                    log("user not found");
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                } else {
                    // 3. create session
                    HttpSession session = request.getSession(true);
                    session.setAttribute(USER, user);

                    response.getWriter().println("Logged in");
                }
            }
        } else {
            // logout

            HttpSession session = request.getSession(false);
            if (session != null) {
                session.setAttribute(USER, null);
                session.invalidate();
            }

            // change Cookie so that Vary: Cookie works
            Cookie c = new Cookie("JSESSIONID", null);
            c.setMaxAge(0);
            response.addCookie(c);

            response.getWriter().println("Logged out");
        }
    } catch (UnavailableException ex) {
        log(ex.getMessage(), ex);
        response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage());
    } catch (EmailNotUniqueException ex) {
        log(ex.getMessage(), ex);
        response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage());
    }
}

From source file:org.regola.security.cas.SingleSignOutFilter.java

public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse,
        final FilterChain filterChain) throws IOException, ServletException {
    final HttpServletRequest request = (HttpServletRequest) servletRequest;

    if ("POST".equals(request.getMethod())) {
        final String logoutRequest = request.getParameter("logoutRequest");

        if (CommonUtils.isNotBlank(logoutRequest)) {

            if (log.isTraceEnabled()) {
                log.trace("Logout request=[" + logoutRequest + "]");
            }/* w w  w  . j ava  2 s.c  o m*/

            final String sessionIdentifier = XmlUtils.getTextForElement(logoutRequest, "SessionIndex");

            if (CommonUtils.isNotBlank(sessionIdentifier)) {
                final HttpSession session = SESSION_MAPPING_STORAGE.removeSessionByMappingId(sessionIdentifier);

                if (session != null) {
                    String sessionID = session.getId();

                    if (log.isDebugEnabled()) {
                        log.debug(
                                "Invalidating session [" + sessionID + "] for ST [" + sessionIdentifier + "]");
                    }

                    try {
                        session.invalidate();
                    } catch (final IllegalStateException e) {
                        log.debug(e, e);
                    }
                }
                return;
            }
        }
    } else {
        final String artifact = request.getParameter(this.artifactParameterName);

        if (CommonUtils.isNotBlank(artifact)) {

            rigeneraSessione(request);
            final HttpSession session = request.getSession();

            if (log.isDebugEnabled() && session != null) {
                log.debug("Storing session identifier for " + session.getId());
            }

            SESSION_MAPPING_STORAGE.addSessionById(artifact, session);
        }
    }

    filterChain.doFilter(servletRequest, servletResponse);
}

From source file:org.regola.security.cas.SingleSignOutFilter.java

private void rigeneraSessione(HttpServletRequest request) {
    HttpSession oldSession = request.getSession(false);

    HashMap<String, Object> tmp = new HashMap<String, Object>();

    if (oldSession != null) {

        Enumeration enumer = oldSession.getAttributeNames();

        while (enumer.hasMoreElements()) {

            String s = (String) enumer.nextElement();

            tmp.put(s, oldSession.getAttribute(s));

        }/*from w  w  w  . j ava 2s  .  co m*/

        log.debug("Sessione " + oldSession.getId() + " valida? " + request.isRequestedSessionIdValid());
        oldSession.invalidate();

    }

    HttpSession newSession = request.getSession(true);

    log.debug("E adesso sessione " + newSession.getId() + " valida? " + request.isRequestedSessionIdValid());

    for (Map.Entry<String, Object> entry : tmp.entrySet()) {

        newSession.setAttribute(entry.getKey(), entry.getValue());

    }
}

From source file:net.lightbody.bmp.proxy.jetty.servlet.SessionDump.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession(false);
    String action = request.getParameter("Action");
    String name = request.getParameter("Name");
    String value = request.getParameter("Value");
    String age = request.getParameter("MaxAge");

    String nextUrl = getURI(request) + "?R=" + redirectCount++;
    if (action.equals("New Session")) {
        session = request.getSession(true);
    } else if (session != null) {
        if (action.equals("Invalidate"))
            session.invalidate();
        else if (action.equals("Set")) {
            session.setAttribute(name, value);
            try {
                int m = Integer.parseInt(age);
                session.setMaxInactiveInterval(m);
            } catch (Exception e) {
                LogSupport.ignore(log, e);
            }//  w  w  w. ja  va 2s. co  m
        } else if (action.equals("Remove"))
            session.removeAttribute(name);
    }

    String encodedUrl = response.encodeRedirectURL(nextUrl);
    response.sendRedirect(encodedUrl);

}

From source file:com.mirth.connect.server.servlets.UserServlet.java

private void logout(HttpServletRequest request, UserController userController, EventController eventController)
        throws ServletException {
    HttpSession session = request.getSession();

    // save the session id before removing them from the session
    Integer userId = (Integer) session.getAttribute(SESSION_USER);
    String sessionId = session.getId();

    // remove the sessions attributes
    session.removeAttribute(SESSION_USER);
    session.removeAttribute(SESSION_AUTHORIZED);

    // invalidate the current sessions
    session.invalidate();

    // set the user status to logged out in the database
    User user = new User();
    user.setId(userId);/*ww  w.  ja  v a2s .  com*/

    try {
        userController.logoutUser(user);
    } catch (ControllerException ce) {
        throw new ServletException(ce);
    }

    // delete any temp tables created for this session
    ControllerFactory.getFactory().createMessageObjectController().removeFilterTable(sessionId);
    eventController.removeFilterTable(sessionId);
}

From source file:com.manydesigns.portofino.actions.user.LoginAction.java

public Resolution logout() {
    Subject subject = SecurityUtils.getSubject();
    subject.logout();/*from   w w  w  . jav  a  2 s .c om*/
    HttpSession session = context.getRequest().getSession(false);
    if (session != null) {
        session.invalidate();
    }

    String msg = ElementsThreadLocals.getText("user.disconnected");
    SessionMessages.addInfoMessage(msg);
    logger.info("User logout");

    return new RedirectResolution("/");
}

From source file:org.jasig.cas.client.session.SingleSignOutFilter.java

public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse,
        final FilterChain filterChain) throws IOException, ServletException {
    final HttpServletRequest request = (HttpServletRequest) servletRequest;

    System.out.println("\n\n=========================================================");

    /*/*from  www  .j a  v  a  2  s  . c o m*/
    System.out.println("SingleSignOutFilter singleLogoutFilter " );
    System.out.println("request.method: " +request.getMethod() );
    System.out.println("request.requestURI: " +request.getRequestURI() );
    System.out.println("request.queryString: " +request.getQueryString() );
      Enumeration enParams = request.getParameterNames(); 
       while(enParams.hasMoreElements()){
      String paramName = (String)enParams.nextElement();
      System.out.println(paramName+": "+request.getParameter(paramName));
       }
       */

    System.out.println("=========================================================\n\n");

    if ("POST".equals(request.getMethod())) {
        final String logoutRequest = CommonUtils.safeGetParameter(request, "logoutRequest");

        if (CommonUtils.isNotBlank(logoutRequest)) {

            if (log.isTraceEnabled()) {
                log.trace("Logout request=[" + logoutRequest + "]");
            }

            final String sessionIdentifier = XmlUtils.getTextForElement(logoutRequest, "SessionIndex");

            if (CommonUtils.isNotBlank(sessionIdentifier)) {
                final HttpSession session = SESSION_MAPPING_STORAGE.removeSessionByMappingId(sessionIdentifier);

                if (session != null) {
                    String sessionID = session.getId();

                    if (log.isDebugEnabled()) {
                        log.debug(
                                "Invalidating session [" + sessionID + "] for ST [" + sessionIdentifier + "]");
                    }

                    try {
                        session.invalidate();
                    } catch (final IllegalStateException e) {
                        log.debug(e, e);
                    }
                }

                return;

            }
        }
    } else {
        final String artifact = CommonUtils.safeGetParameter(request, this.artifactParameterName);

        if (CommonUtils.isNotBlank(artifact)) {
            final HttpSession session = request.getSession(true);

            if (log.isDebugEnabled()) {
                log.debug("Storing session identifier for " + session.getId());
            }

            try {
                SESSION_MAPPING_STORAGE.removeBySessionById(session.getId());
            } catch (final Exception e) {
                // ignore if the session is already marked as invalid.  Nothing we can do!
            }
            SESSION_MAPPING_STORAGE.addSessionById(artifact, session);
        } else {
            log.debug("No Artifact Provided; no action taking place.");
        }
    }

    // filterChain.doFilter(servletRequest, httpServletResponseWrapper);

    filterChain.doFilter(servletRequest, servletResponse);

}

From source file:uk.ac.ed.epcc.webapp.servlet.DefaultServletService.java

/**invalidate the servlet session and optionally remove the session cookie.
 *
 * // w w  w  . j  a v  a  2s .  co m
 * 
 * @param remove_cookie should cookie be removed
 * 
 */
public void logout(boolean remove_cookie) {
    HttpSession sess = getSession();
    if (sess != null) {
        sess.invalidate();
    }
    if (remove_cookie) {
        HttpServletRequest request = getRequest();
        if (request != null) {
            Cookie[] cookies = request.getCookies();
            if (cookies != null && cookies.length > 0) {
                for (Cookie c : cookies) {
                    if (c.getName().equalsIgnoreCase("JSESSIONID") || getContext()
                            .getBooleanParameter(LOGOUT_REMOVE_COOKIE_PREFIX + c.getName(), false)) {
                        Cookie c2 = (Cookie) c.clone();
                        c2.setMaxAge(0); // This should request a delete
                        if (c2.getPath() == null) {
                            String contextPath = request.getContextPath();
                            c2.setPath(contextPath + "/"); // browser did not include path. This will only work if path matched exactly
                        }
                        c2.setValue("");
                        ((HttpServletResponse) res).addCookie(c2);
                    }
                }
            }
        }
    }
}