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.esupportail.publisher.security.CustomSingleSignOutHandler.java

/**
 * Destroys the current HTTP session for the given CAS logout request.
 *
 * @param request HTTP request containing a CAS logout message.
 *///from  w  w  w  . j  av  a 2  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);
            }
            this.logoutStrategy.logout(request);
        }
    }
}

From source file:com.sammyun.controller.shop.LoginController.java

/**
 * <??>?? <??>/*from w ww.  j  a va 2 s. c om*/
 * 
 * @param username
 * @param request
 * @param response
 * @param session
 * @param member
 * @see [?#?#?]
 */
protected void syncCart(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        Member member) {

    Map<String, Object> attributes = new HashMap<String, Object>();
    Enumeration<?> keys = session.getAttributeNames();
    while (keys.hasMoreElements()) {
        String key = (String) keys.nextElement();
        attributes.put(key, session.getAttribute(key));
    }
    session.invalidate();
    session = request.getSession();
    for (Entry<String, Object> entry : attributes.entrySet()) {
        session.setAttribute(entry.getKey(), entry.getValue());
    }

    session.setAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME, new Principal(member.getId(), member.getUsername()));
    WebUtils.addCookie(request, response, Member.USERNAME_COOKIE_NAME, member.getUsername());
}

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

@Override
@DontCheckAuthorized/*from www.j  a  v a 2 s .c om*/
public void logout() {
    // Audit the logout request but don't block it
    isUserAuthorized();

    HttpSession session = request.getSession();

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

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

    try {
        userController.logoutUser(user);
    } catch (ControllerException e) {
        throw new MirthApiException(e);
    }
}

From source file:org.openmrs.web.servlet.LoginServlet.java

/**
 * Regenerates session id after each login attempt.
 * @param request// w  w  w .j  a  va 2s  . c  o m
 */
private void regenerateSession(HttpServletRequest request) {

    HttpSession oldSession = request.getSession();

    Enumeration attrNames = oldSession.getAttributeNames();
    Properties props = new Properties();

    if (attrNames != null) {
        while (attrNames.hasMoreElements()) {
            String key = (String) attrNames.nextElement();
            props.put(key, oldSession.getAttribute(key));
        }

        //Invalidating previous session
        oldSession.invalidate();
        //Generate new session
        HttpSession newSession = request.getSession(true);
        attrNames = props.keys();

        while (attrNames.hasMoreElements()) {
            String key = (String) attrNames.nextElement();
            newSession.setAttribute(key, props.get(key));
        }
    }
}

From source file:com.sourcesense.alfresco.opensso.AlfrescoOpenSSOFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    HttpSession httpSession = httpRequest.getSession();

    request.setCharacterEncoding("UTF-8");

    SSOToken token = getOpenSSOClient().createTokenFrom(httpRequest);

    boolean isLoginRequest = isLoginRequest(httpRequest);
    boolean isLogoutRequest = isLogoutRequest(httpRequest);
    boolean isGuestRequest = (token == null && !isLoginRequest && !isLogoutRequest);
    boolean isNormalRequest = (token != null && !isLoginRequest && !isLogoutRequest);

    if (isLoginRequest) {
        httpSession.invalidate();
        httpResponse.sendRedirect(buildURLForRedirect(request));
    }/* w ww. ja  v  a2 s.c  o m*/

    if (isGuestRequest) {
        getAlfrescoFacade().authenticateAsGuest(httpSession);
        chain.doFilter(request, response);
    }

    if (isLogoutRequest) {
        doLogout(httpSession, token);
        httpResponse.sendRedirect(buildURLForRedirect(request));
    }

    if (isNormalRequest) {
        String principal = getOpenSSOClient().getPrincipal(token);
        if (!getAlfrescoFacade().existUser(principal)) {
            String email = getOpenSSOClient().getUserAttribute(OpenSSOClient.ATTR_EMAIL, token);
            String fullName = getOpenSSOClient().getUserAttribute(OpenSSOClient.ATTR_FULL_NAME, token);
            String firstName = getOpenSSOClient().getUserAttribute(OpenSSOClient.ATTR_LAST_NAME, token);
            getAlfrescoFacade().createUser(principal, email, firstName, fullName);
        }
        List<String> groups = getOpenSSOClient().getGroups(token);
        getAlfrescoFacade().createOrUpdateGroups(principal, groups);
        getAlfrescoFacade().setAuthenticatedUser(httpRequest, httpResponse, httpSession, principal);
        chain.doFilter(request, response);
    }

}

From source file:com.netspective.sparx.security.HttpLoginManager.java

public void logout(HttpServletValueContext vc) {
    vc.getProject().getScrollStates().removeActiveState(vc);

    if (isAllowRememberUserId()) {
        Cookie cookie = new Cookie(getRememberUserIdCookieName(), "");
        cookie.setPath(getRememberPasswordCookiePath(vc));
        cookie.setMaxAge(-1);/*  w ww. ja  va 2 s  .  c  o m*/
        vc.getHttpResponse().addCookie(cookie);
        cookie = new Cookie(getRememberPasswordCookieName(), "");
        cookie.setPath(getRememberPasswordCookiePath(vc));
        cookie.setMaxAge(-1);
        vc.getHttpResponse().addCookie(cookie);
    }

    final HttpServletRequest req = vc.getHttpRequest();
    final MutableAuthenticatedUser user = (MutableAuthenticatedUser) getAuthenticatedUser(req);
    final HttpSession session = req.getSession();
    if (user != null) {
        registerLogout(vc, user);
        session.removeAttribute(getAuthenticatedUserSessionAttrName());
    }
    session.invalidate();
}

From source file:de.itsvs.cwtrpc.controller.RemoteServiceControllerServlet.java

protected void invalidateSession(HttpServletRequest request) throws ServletException {
    final HttpSession session;

    session = request.getSession(false);
    if (session != null) {
        if (log.isDebugEnabled()) {
            log.debug("Invalidating session " + session.getId());
        }/* w w w . jav a  2 s.co  m*/
        session.invalidate();
    }
}

From source file:org.apache.struts.webapp.example.LogoffAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    // Extract attributes we will need
    HttpSession session = request.getSession();
    User user = (User) session.getAttribute(Constants.USER_KEY);

    // Process this user logoff
    if (user != null) {
        if (log.isDebugEnabled()) {
            log.debug(//  ww  w .  ja  v a  2  s  .  c om
                    "LogoffAction: User '" + user.getUsername() + "' logged off in session " + session.getId());
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("LogoffActon: User logged off in session " + session.getId());
        }
    }
    session.removeAttribute(Constants.SUBSCRIPTION_KEY);
    session.removeAttribute(Constants.USER_KEY);
    session.invalidate();

    // Forward control to the specified success URI
    return (mapping.findForward("success"));

}

From source file:com.googlesource.gerrit.plugins.github.oauth.OAuthWebFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    log.debug("OAuthWebFilter(" + httpRequest.getRequestURL() + ") code=" + request.getParameter("code"));

    Cookie gerritCookie = getGerritCookie(httpRequest);
    try {/*from ww w . j a va2s.c  o m*/
        GitHubLogin ghLogin = loginProvider.get(httpRequest);

        if (OAuthProtocol.isOAuthLogout(httpRequest)) {
            logout(request, response, chain, httpRequest);
        } else if (OAuthProtocol.isOAuthRequest(httpRequest) && !ghLogin.isLoggedIn()) {
            login(request, httpRequest, httpResponse, ghLogin);
        } else {
            if (ghLogin != null && ghLogin.isLoggedIn()) {
                httpRequest = new AuthenticatedHttpRequest(httpRequest, config.httpHeader,
                        ghLogin.getMyself().getLogin(), config.oauthHttpHeader,
                        GITHUB_EXT_ID + ghLogin.getToken().accessToken);
            }

            if (OAuthProtocol.isOAuthFinalForOthers(httpRequest)) {
                httpResponse.sendRedirect(OAuthProtocol.getTargetOAuthFinal(httpRequest));
            } else {
                chain.doFilter(httpRequest, response);
            }
        }
    } finally {
        HttpSession httpSession = httpRequest.getSession();
        if (gerritCookie != null && httpSession != null) {
            String gerritCookieValue = gerritCookie.getValue();
            String gerritSessionValue = (String) httpSession.getAttribute("GerritAccount");

            if (gerritSessionValue == null) {
                httpSession.setAttribute("GerritAccount", gerritCookieValue);
            } else if (!gerritSessionValue.equals(gerritCookieValue)) {
                httpSession.invalidate();
            }
        }
    }
}

From source file:org.springframework.test.web.servlet.htmlunit.HtmlUnitRequestBuilderTest.java

@Test
public void buildRequestSessionInvalidate() throws Exception {
    String sessionId = "session-id";
    webRequest.setAdditionalHeader("Cookie", "JSESSIONID=" + sessionId);

    MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
    HttpSession sessionToRemove = actualRequest.getSession();
    sessionToRemove.invalidate();

    assertThat(!sessions.containsKey(sessionToRemove.getId()));
    assertSingleSessionCookie("JSESSIONID=" + sessionToRemove.getId()
            + "; Expires=Thu, 01-Jan-1970 00:00:01 GMT; Path=/test; Domain=example.com");

    webRequest.removeAdditionalHeader("Cookie");
    requestBuilder = new HtmlUnitRequestBuilder(sessions, cookieManager, webRequest);

    actualRequest = requestBuilder.buildRequest(servletContext);

    assertThat(actualRequest.getSession().isNew()).isTrue();
    assertThat(!sessions.containsKey(sessionToRemove.getId()));
}