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:hudson.security.SecurityRealm.java

/**
 * Handles the logout processing.//from ww  w .j ava  2s.c om
 *
 * <p>
 * The default implementation erases the session and do a few other clean up, then
 * redirect the user to the URL specified by {@link #getPostLogOutUrl(StaplerRequest, Authentication)}.
 *
 * @since 1.314
 */
public void doLogout(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
    HttpSession session = req.getSession(false);
    if (session != null)
        session.invalidate();
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    SecurityContextHolder.clearContext();

    // reset remember-me cookie
    Cookie cookie = new Cookie(ACEGI_SECURITY_HASHED_REMEMBER_ME_COOKIE_KEY, "");
    cookie.setMaxAge(0);
    cookie.setSecure(req.isSecure());
    cookie.setHttpOnly(true);
    cookie.setPath(req.getContextPath().length() > 0 ? req.getContextPath() : "/");
    rsp.addCookie(cookie);

    rsp.sendRedirect2(getPostLogOutUrl(req, auth));
}

From source file:com.expressui.core.MainApplication.java

private void invalidateSession() {
    WebApplicationContext context = (WebApplicationContext) getContext();
    HttpSession httpSession = context.getHttpSession();
    httpSession.invalidate();
}

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

/**
 * Process the specified HTTP request, and create the corresponding HTTP
 * response (or forward to another web component that will create it).
 * Return an <code>ActionForward</code> instance describing where and how
 * control should be forwarded, or <code>null</code> if the response has
 * already been completed./*from   w w w  .j  a va  2  s  . c om*/
 *
 * @param mapping The ActionMapping used to select this instance
 * @param form The optional ActionForm bean for this request (if any)
 * @param request The HTTP request we are processing
 * @param response The HTTP response we are creating
 *
 * @exception Exception if business logic throws an exception
 */
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    // Extract attributes we will need
    Locale locale = getLocale(request);
    MessageResources messages = getResources(request);
    HttpSession session = request.getSession();
    User user = (User) session.getAttribute(Constants.USER_KEY);

    // Process this user logoff
    if (user != null) {
        if (log.isDebugEnabled()) {
            log.debug(
                    "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:org.silverpeas.core.web.authentication.AuthenticationServlet.java

/**
 * Ask for an authentication for the user behind the incoming HTTP request from a form.
 *
 * @param servletRequest the HTTP request.
 * @param servletResponse the HTTP response.
 * @throws IOException when an error occurs while processing the request or sending the response.
 * @throws javax.servlet.ServletException
 *//*from  w ww.ja va 2 s  .co  m*/
@Override
public void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws IOException, ServletException {
    HttpRequest request = HttpRequest.decorate(servletRequest);
    // get an existing session or creates a new one.
    HttpSession session = request.getSession();

    if (!StringUtil.isDefined(request.getCharacterEncoding())) {
        request.setCharacterEncoding(CharEncoding.UTF_8);
    }
    if (request.isWithinAnonymousUserSession()) {
        session.invalidate();
    }

    // Get the authentication settings
    SettingBundle authenticationSettings = ResourceLocator
            .getSettingBundle("org.silverpeas.authentication.settings.authenticationSettings");
    boolean securedAccess = request.isSecure();
    boolean isNewEncryptMode = StringUtil.isDefined(request.getParameter("Var2"));
    AuthenticationParameters authenticationParameters = new AuthenticationParameters(request);
    String domainId = getDomain(request, authenticationParameters, authenticationSettings);
    AuthenticationCredential credential = AuthenticationCredential
            .newWithAsLogin(authenticationParameters.getLogin())
            .withAsPassword(authenticationParameters.getPassword()).withAsDomainId(domainId);

    String authenticationKey = authenticate(request, authenticationParameters, domainId);
    String url = "";

    // Verify if the user can try again to login.
    UserCanTryAgainToLoginVerifier userCanTryAgainToLoginVerifier = AuthenticationUserVerifierFactory
            .getUserCanTryAgainToLoginVerifier(credential);
    userCanTryAgainToLoginVerifier.clearSession(request);

    if (!authService.isInError(authenticationKey)) {

        // Clearing user connection attempt cache.
        userCanTryAgainToLoginVerifier.clearCache();

        if (domainId != null) {
            storeDomain(servletResponse, domainId, securedAccess);
        }
        storeLogin(servletResponse, isNewEncryptMode, authenticationParameters.getLogin(), securedAccess);

        // if required by user, store password in cookie
        storePassword(servletResponse, authenticationParameters.getStoredPassword(), isNewEncryptMode,
                authenticationParameters.getClearPassword(), securedAccess);

        if (request.getAttribute("skipTermsOfServiceAcceptance") == null) {
            UserMustAcceptTermsOfServiceVerifier verifier = AuthenticationUserVerifierFactory
                    .getUserMustAcceptTermsOfServiceVerifier(credential);
            try {
                verifier.verify();
            } catch (AuthenticationUserMustAcceptTermsOfService authenticationUserMustAcceptTermsOfService) {
                forward(request, servletResponse, verifier.getDestination(request));
                return;
            }
        }

        if (mandatoryQuestionChecker.check(request, authenticationKey)) {
            forward(request, servletResponse, mandatoryQuestionChecker.getDestination());
            return;
        }

        String absoluteUrl = silverpeasSessionOpener.openSession(request, authenticationKey);
        // fetch the new opened session
        session = request.getSession(false);
        session.setAttribute("Silverpeas_pwdForHyperlink", authenticationParameters.getClearPassword());
        writeSessionCookie(servletResponse, session, securedAccess);
        servletResponse.sendRedirect(servletResponse.encodeRedirectURL(absoluteUrl));
        return;
    }
    // Authentication failed : remove password from cookies to avoid infinite loop
    removeStoredPassword(servletResponse, securedAccess);
    if (authenticationParameters.isCasMode()) {
        url = "/admin/jsp/casAuthenticationError.jsp";
    } else {
        if (AuthenticationService.ERROR_INCORRECT_LOGIN_PWD.equals(authenticationKey)
                || AuthenticationService.ERROR_INCORRECT_LOGIN_PWD_DOMAIN.equals(authenticationKey)) {
            try {
                if (userCanTryAgainToLoginVerifier.isActivated()) {
                    storeLogin(servletResponse, isNewEncryptMode, authenticationParameters.getLogin(),
                            securedAccess);
                    storeDomain(servletResponse, domainId, securedAccess);
                }
                if (AuthenticationService.ERROR_INCORRECT_LOGIN_PWD.equals(authenticationKey)) {
                    url = userCanTryAgainToLoginVerifier.verify().performRequestUrl(request,
                            "/Login.jsp?ErrorCode=" + INCORRECT_LOGIN_PWD);
                } else if (AuthenticationService.ERROR_INCORRECT_LOGIN_PWD_DOMAIN.equals(authenticationKey)) {
                    url = userCanTryAgainToLoginVerifier.verify().performRequestUrl(request,
                            "/Login.jsp?ErrorCode=" + INCORRECT_LOGIN_PWD_DOMAIN);
                }
            } catch (AuthenticationNoMoreUserConnectionAttemptException e) {
                url = userCanTryAgainToLoginVerifier.getErrorDestination();
            }
        } else if (UserCanLoginVerifier.ERROR_USER_ACCOUNT_BLOCKED.equals(authenticationKey)
                || UserCanLoginVerifier.ERROR_USER_ACCOUNT_DEACTIVATED.equals(authenticationKey)) {
            if (userCanTryAgainToLoginVerifier.isActivated()
                    || StringUtil.isDefined(userCanTryAgainToLoginVerifier.getUser().getId())) {
                // If user can try again to login verifier is activated or if the user has been found
                // from credential, the login and the domain are stored
                storeLogin(servletResponse, isNewEncryptMode, authenticationParameters.getLogin(),
                        securedAccess);
                storeDomain(servletResponse, domainId, securedAccess);
                url = AuthenticationUserVerifierFactory
                        .getUserCanLoginVerifier(userCanTryAgainToLoginVerifier.getUser())
                        .getErrorDestination();
            } else {
                if (AuthenticationService.ERROR_INCORRECT_LOGIN_PWD.equals(authenticationKey)) {
                    url = "/Login.jsp?ErrorCode=" + INCORRECT_LOGIN_PWD;
                } else if (AuthenticationService.ERROR_INCORRECT_LOGIN_PWD_DOMAIN.equals(authenticationKey)) {
                    url = "/Login.jsp?ErrorCode=" + INCORRECT_LOGIN_PWD_DOMAIN;
                }
            }
        } else if (AuthenticationService.ERROR_PWD_EXPIRED.equals(authenticationKey)) {
            String allowPasswordChange = (String) session.getAttribute(Authentication.PASSWORD_CHANGE_ALLOWED);
            if (StringUtil.getBooleanValue(allowPasswordChange)) {
                SettingBundle settings = ResourceLocator
                        .getSettingBundle("org.silverpeas.authentication.settings.passwordExpiration");
                url = settings.getString("passwordExpiredURL") + "?login=" + authenticationParameters.getLogin()
                        + "&domainId=" + domainId;
            } else {
                url = "/Login.jsp?ErrorCode=" + AuthenticationService.ERROR_PWD_EXPIRED;
            }
        } else if (AuthenticationService.ERROR_PWD_MUST_BE_CHANGED.equals(authenticationKey)) {
            String allowPasswordChange = (String) session.getAttribute(Authentication.PASSWORD_CHANGE_ALLOWED);
            if (StringUtil.getBooleanValue(allowPasswordChange)) {
                SettingBundle settings = ResourceLocator
                        .getSettingBundle("org.silverpeas.authentication.settings.passwordExpiration");
                url = settings.getString("passwordExpiredURL") + "?login=" + authenticationParameters.getLogin()
                        + "&domainId=" + domainId;
            } else {
                url = "/Login.jsp?ErrorCode=" + AuthenticationService.ERROR_PWD_EXPIRED;
            }
        } else if (UserMustChangePasswordVerifier.ERROR_PWD_MUST_BE_CHANGED_ON_FIRST_LOGIN
                .equals(authenticationKey)) {
            // User has been successfully authenticated, but he has to change his password on his
            // first login and login / domain id can be stored
            storeLogin(servletResponse, isNewEncryptMode, authenticationParameters.getLogin(), securedAccess);
            storeDomain(servletResponse, domainId, securedAccess);
            url = AuthenticationUserVerifierFactory.getUserMustChangePasswordVerifier(credential)
                    .getDestinationOnFirstLogin(request);
            forward(request, servletResponse, url);
            return;
        } else if (authenticationParameters.isSsoMode()) {
            // User has been successfully authenticated on AD, but he has no user account on Silverpeas
            // -> login / domain id can be stored
            storeDomain(servletResponse, domainId, securedAccess);
            storeLogin(servletResponse, isNewEncryptMode, authenticationParameters.getLogin(), securedAccess);
            url = "/Login.jsp?ErrorCode=" + SSO_UNEXISTANT_USER_ACCOUNT;
        } else {
            url = "/Login.jsp?ErrorCode=" + TECHNICAL_ISSUE;
        }
    }
    servletResponse
            .sendRedirect(servletResponse.encodeRedirectURL(URLUtil.getFullApplicationURL(request) + url));
}

From source file:edu.vt.middleware.ldap.servlets.session.DefaultSessionManager.java

/**
 * This performs any actions necessary to logout the suppled session.
 *
 * @param  session  <code>HttpSession</code>
 *
 * @throws  ServletException  if an error occurs cleaning up the session
 *//*from  ww w .j a  v  a  2s  . com*/
public void logout(final HttpSession session) throws ServletException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Begin logout method");
    }
    if (this.sessionId != null) {
        final String user = (String) session.getAttribute(this.sessionId);
        session.removeAttribute(this.sessionId);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Removed session attribute " + this.sessionId + " for " + user);
        }
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Could not remove session attribute, value is null");
        }
    }
    if (this.invalidateSession) {
        session.invalidate();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Session invalidated");
        }
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Session was not invalidated");
        }
    }
}

From source file:com.erudika.scoold.utils.ScooldUtils.java

public void clearSession(HttpServletRequest req, HttpServletResponse res) {
    if (req != null) {
        HttpSession session = req.getSession(false);
        if (session != null) {
            session.invalidate();
        }/*from  ww w.  j  a  va  2s.c om*/
        HttpUtils.removeStateParam(Config.AUTH_COOKIE, req, res);
        HttpUtils.removeStateParam(CSRF_COOKIE, req, res);
    }
}

From source file:com.virtusa.akura.common.controller.LoginController.java

/**
 * handle GET requests for Student_details view.
 * //from w  w  w .j  a va 2 s  .  com
 * @param model - ModelMap
 * @param session - {@link HttpSession}
 * @return the name of the view.
 */
@RequestMapping(value = USER_LOGIN_HTM, method = RequestMethod.GET)
public String showUserLoginConsole(ModelMap model, HttpSession session) {

    session.invalidate();
    return LOGIN;
}

From source file:org.alfresco.repo.webdav.auth.BaseKerberosAuthenticationFilter.java

/**
 * Restart the Kerberos logon process/* w ww . j a  v  a 2s  . co m*/
 * 
 * @param context ServletContext
 * @param req HttpServletRequest
 * @param resp HttpServletResponse
 * @throws IOException
 */
public void restartLoginChallenge(ServletContext context, HttpServletRequest req, HttpServletResponse resp)
        throws IOException {
    HttpSession session = req.getSession(false);
    if (session != null) {
        if (getLogger().isDebugEnabled())
            getLogger().debug("Clearing session.");
        session.invalidate();
    }
    logonStartAgain(context, req, resp);
}

From source file:org.wso2.carbon.identity.authenticator.webseal.WebSealAuthenticator.java

public void logout() {

    String loggedInUser;//from  w w w.  j  a v a  2 s . co m
    String delegatedBy;
    Date currentTime = Calendar.getInstance().getTime();
    SimpleDateFormat date = new SimpleDateFormat("'['yyyy-MM-dd HH:mm:ss,SSSS']'");
    HttpSession session = getHttpSession();

    if (session != null) {
        loggedInUser = (String) session.getAttribute(ServerConstants.USER_LOGGED_IN);
        delegatedBy = (String) session.getAttribute("DELEGATED_BY");
        if (delegatedBy == null) {
            log.info("'" + loggedInUser + "' logged out at " + date.format(currentTime));
        } else {
            log.info("'" + loggedInUser + "' logged out at " + date.format(currentTime) + " delegated by "
                    + delegatedBy);
        }
        session.invalidate();
    }
}

From source file:org.opencms.jsp.CmsJspLoginBean.java

/**
 * Logs a system user into OpenCms.<p>
 * /*from  w ww  . jav  a2s.co  m*/
 * Note that if a login project name is provided, this project must exist,
 * otherwise the login is regarded as a failure even if the user data was correct.<p>
 * 
 * @param userName the users name
 * @param password the password
 * @param projectName the project to switch to after login (if null project is not switched)
 */
public void login(String userName, String password, String projectName) {

    HttpSession session = null;
    m_loginException = null;
    try {

        // login the user and create a new session
        getCmsObject().loginUser(userName, password, getRequestContext().getRemoteAddress());

        // make sure we have a new session after login for security reasons
        session = getRequest().getSession(false);
        if (session != null) {
            session.invalidate();
        }
        session = getRequest().getSession(true);
        if (projectName != null) {
            // if this fails, the login is regarded as a failure as well
            getCmsObject().getRequestContext().setCurrentProject(getCmsObject().readProject(projectName));
        }

    } catch (CmsException e) {
        // the login has failed
        m_loginException = e;
    }
    if (m_loginException == null) {
        // login was successful
        if (LOG.isInfoEnabled()) {
            LOG.info(Messages.get().getBundle().key(Messages.LOG_LOGIN_SUCCESSFUL_3, userName,
                    getRequestContext().addSiteRoot(getRequestContext().getUri()),
                    getRequestContext().getRemoteAddress()));
        }
    } else {
        // login was not successful
        if (session != null) {
            session.invalidate();
        }

        if (m_loginException instanceof CmsAuthentificationException) {

            // the authentication of the user failed
            if (org.opencms.security.Messages.ERR_LOGIN_FAILED_DISABLED_2 == m_loginException
                    .getMessageContainer().getKey()) {

                // the user has been disabled
                LOG.warn(Messages.get().getBundle().key(Messages.LOG_LOGIN_FAILED_DISABLED_3, userName,
                        getRequestContext().addSiteRoot(getRequestContext().getUri()),
                        getRequestContext().getRemoteAddress()));

            } else if (org.opencms.security.Messages.ERR_LOGIN_FAILED_TEMP_DISABLED_4 == m_loginException
                    .getMessageContainer().getKey()) {

                // the user has been disabled
                LOG.warn(Messages.get().getBundle().key(Messages.LOG_LOGIN_FAILED_TEMP_DISABLED_5,
                        new Object[] { userName, getRequestContext().addSiteRoot(getRequestContext().getUri()),
                                getRequestContext().getRemoteAddress(),
                                m_loginException.getMessageContainer().getArgs()[2],
                                m_loginException.getMessageContainer().getArgs()[3] }));

            } else if (org.opencms.security.Messages.ERR_LOGIN_FAILED_NO_USER_2 == m_loginException
                    .getMessageContainer().getKey()) {

                // the requested user does not exist in the database
                LOG.warn(Messages.get().getBundle().key(Messages.LOG_LOGIN_FAILED_NO_USER_3, userName,
                        getRequestContext().addSiteRoot(getRequestContext().getUri()),
                        getRequestContext().getRemoteAddress()));

            } else if (org.opencms.security.Messages.ERR_LOGIN_FAILED_WITH_MESSAGE_1 == m_loginException
                    .getMessageContainer().getKey()) {

                // logins have been disabled by the administration
                long endTime = CmsLoginMessage.DEFAULT_TIME_END;
                if (OpenCms.getLoginManager().getLoginMessage() != null) {
                    endTime = OpenCms.getLoginManager().getLoginMessage().getTimeEnd();
                }
                LOG.info(Messages.get().getBundle().key(Messages.LOG_LOGIN_FAILED_WITH_MESSAGE_4,
                        new Object[] { userName, getRequestContext().addSiteRoot(getRequestContext().getUri()),
                                getRequestContext().getRemoteAddress(), new Date(endTime) }));

            } else {

                // the user exists, so the password must have been wrong
                CmsMessageContainer message = Messages.get().container(Messages.LOG_LOGIN_FAILED_3, userName,
                        getRequestContext().addSiteRoot(getRequestContext().getUri()),
                        getRequestContext().getRemoteAddress());
                if (OpenCms.getDefaultUsers().isUserAdmin(userName)) {
                    // someone tried to log in as "Admin", log this in a higher channel
                    LOG.error(message.key());
                } else {
                    LOG.warn(message.key());
                }
            }
        } else {
            // the error was database related, there may be an issue with the setup 
            // write the exception to the log as well
            LOG.error(Messages.get().getBundle().key(Messages.LOG_LOGIN_FAILED_DB_REASON_3, userName,
                    getRequestContext().addSiteRoot(getRequestContext().getUri()),
                    getRequestContext().getRemoteAddress()), m_loginException);
        }
    }
}