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:net.naijatek.myalumni.modules.common.presentation.action.SecurityAction.java

/**
* Performs the logging out of users// w w w  .j  a v a  2s.  com
*
* @param mapping ActionMapping
* @param form ActionForm
* @param request HttpServletRequest
* @param response HttpServletResponse
* @throws Exception
* @return ActionForward
*/
public ActionForward logout(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    HttpSession session = request.getSession(true);

    int sessionTimeout = setupSessionTimeout(session);
    MemberVO token = getCurrentLoggedInUser(request);
    if (token != null) {
        OnlineUserManager manager = OnlineUserManager.getInstance();
        manager.removeOnlineUser(token.getMemberUserName());
        ServletContext sCtx = request.getSession().getServletContext();
        sCtx.setAttribute("onlineusers", manager.getOnlineUsers(sessionTimeout));
    }

    if (session != null) {
        session.removeAttribute(BaseConstants.USER_CONTAINER);
        logger.info("User successfully logged out...");
        session.invalidate();
    }

    return (mapping.findForward(BaseConstants.FWD_SUCCESS));
}

From source file:com.tohours.imo.module.AttractModule.java

@At
@Ok(">>:/attract/index.jsp")
// ??,??
public void logout(HttpSession session) {
    session.invalidate();
}

From source file:com.oic.net.Callback.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession();
    String code = request.getParameter("code");
    if (request.getParameter("code") == null) { //OAuth??code????
        response.sendRedirect("/");
    } else if (request.getParameter("register") != null) { //ID?
        session.setAttribute("alreadyId", true);
        return;/* ww  w . j a  va  2  s .co  m*/
    }
    if (session.isNew()) {
        session.setMaxInactiveInterval(300);
    }
    String email = "";
    try {
        getToken(code);
        System.out.println(code);
        email = getEmailAddress();
    } catch (Exception e) {
        e.printStackTrace();
    }
    Pattern pattern = Pattern.compile("@oic.jp$");
    Matcher matcher = pattern.matcher(email);
    if (matcher.find()) {
        Pattern numberPattern = Pattern.compile("^[a-zA-Z][0-9]{4}");
        Matcher numberMatcher = numberPattern.matcher(email.toLowerCase());
        if (!numberMatcher.find()) {
            response.getWriter().println("????????");
            session.invalidate();
            return;
        }

        String studentNumber = numberMatcher.group();
        String key = DigestUtils.md5Hex(String.valueOf(new Date().getTime()));
        session.setAttribute("studentNumber", studentNumber);
        session.setAttribute("key", key); //md5??
        registerData(studentNumber, key, session);
        response.sendRedirect("/");
    } else {
        response.getWriter().println("????????");
        session.invalidate();
    }

}

From source file:org.jasig.portal.spring.security.preauth.PortalPreAuthenticatedProcessingFilter.java

private void doPortalAuthentication(HttpServletRequest request) {
    // Clear out the existing session for the user if they have one
    String targetUid = null;/*from   w ww .ja  va  2 s .  c o m*/
    String originalUid = null;
    boolean swap = false;
    if (request.isRequestedSessionIdValid()) {
        try {
            HttpSession s = request.getSession(false);

            if (s != null) {
                //Check if this is a swapped user hitting the Login servlet
                originalUid = this.identitySwapperManager.getOriginalUsername(s);
            }

            //No original person in session so check for swap request
            if (originalUid == null) {
                targetUid = this.identitySwapperManager.getTargetUsername(s);
                if (targetUid != null) {
                    final IPerson person = personManager.getPerson(request);
                    originalUid = person.getName();
                    swap = true;
                }
            } else {
                final IPerson person = personManager.getPerson(request);
                targetUid = person.getName();
            }

            if (s != null) {
                s.invalidate();
            }
        } catch (IllegalStateException ise) {
            // ISE indicates session was already invalidated.
            // This is fine.  This servlet trying to guarantee that the session has been invalidated;
            // it doesn't have to insist that it is the one that invalidated it.
            if (logger.isTraceEnabled()) {
                logger.trace("LoginServlet attempted to invalidate an already invalid session.", ise);
            }
        }
    }

    //  Create the user's session
    HttpSession s = request.getSession(true);

    final String requestedProfile = request.getParameter(LoginController.REQUESTED_PROFILE_KEY);
    if (requestedProfile != null) {
        s.setAttribute(SessionAttributeProfileMapperImpl.DEFAULT_SESSION_ATTRIBUTE_NAME, requestedProfile);
    }

    IPerson person = null;
    try {
        final HashMap<String, String> principals;
        final HashMap<String, String> credentials;

        // Get the person object associated with the request
        person = personManager.getPerson(request);

        //If doing an identity swap
        if (targetUid != null && originalUid != null) {
            if (swap) {
                swapperLog.warn("Swapping identity for '" + originalUid + "' to '" + targetUid + "'");

                //Track the originating user
                this.identitySwapperManager.setOriginalUser(s, originalUid, targetUid);

                //Setup the swapped person
                person.setUserName(targetUid);
            } else {
                swapperLog.warn("Reverting swapped identity from '" + targetUid + "' to '" + originalUid + "'");

                person.setUserName(originalUid);
            }

            //Setup the custom security context
            final IdentitySwapperPrincipal identitySwapperPrincipal = new IdentitySwapperPrincipal(person);
            final IdentitySwapperSecurityContext identitySwapperSecurityContext = new IdentitySwapperSecurityContext(
                    identitySwapperPrincipal);
            person.setSecurityContext(identitySwapperSecurityContext);

            principals = new HashMap<String, String>();
            credentials = new HashMap<String, String>();
        }
        //Norm authN path
        else {
            // WE grab all of the principals and credentials from the request and load
            // them into their respective HashMaps.
            principals = getPropertyFromRequest(principalTokens, request);
            credentials = getPropertyFromRequest(credentialTokens, request);
        }

        // Attempt to authenticate using the incoming request
        authenticationService.authenticate(request, principals, credentials, person);
    } catch (Exception e) {
        // Log the exception
        logger.error("Exception authenticating the request", e);
        // Reset everything
        request.getSession(false).invalidate();
        // Add the authentication failure
        request.getSession(true).setAttribute(LoginController.AUTH_ERROR_KEY, Boolean.TRUE);
    }
}

From source file:at.gv.egovernment.moa.id.configuration.struts.action.IndexAction.java

public String logout() {
    HttpSession session = request.getSession(false);

    if (session != null) {
        if (MiscUtil.isNotEmpty((String) session.getAttribute(Constants.SESSION_SLOSUCCESS)))
            addActionMessage((String) session.getAttribute(Constants.SESSION_SLOSUCCESS));

        if (MiscUtil.isNotEmpty((String) session.getAttribute(Constants.SESSION_SLOERROR)))
            addActionError((String) session.getAttribute(Constants.SESSION_SLOERROR));

        session.invalidate();

    }/*from   w ww .j a  va  2  s  .c  o  m*/

    return Constants.STRUTS_SUCCESS;
}

From source file:at.gv.egovernment.moa.id.configuration.struts.action.IndexAction.java

private HttpSession generateNewJSession(HttpServletRequest request) {
    HttpSession session = request.getSession(false);

    if (session != null) {

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

        Enumeration<String> enames = session.getAttributeNames();
        while (enames.hasMoreElements()) {
            String name = enames.nextElement();
            if (!name.equals("JSESSIONID"))
                attributes.put(name, session.getAttribute(name));
        }//from  w w w  . ja v  a2s . c om
        session.invalidate();

        session = request.getSession(true);
        for (Entry<String, Object> et : attributes.entrySet())
            session.setAttribute(et.getKey(), et.getValue());

    } else
        session = request.getSession(true);

    return session;
}

From source file:nl.strohalm.cyclos.utils.LoginHelper.java

/**
 * Returns the currently logged user, ensuring there is one
 *//*from   w w  w.ja  v  a2s.  c o m*/
public User validateLoggedUser(final HttpServletRequest request) {
    final HttpSession session = request.getSession();

    // Find the logged user
    final User user = getLoggedUser(request);
    if (user == null) {
        throw new LoggedOutException();
    }
    // Find the registered logged user for the session id
    User serviceUser;
    try {
        serviceUser = accessService.getLoggedUser(session.getId());
    } catch (final NotConnectedException e) {
        throw new LoggedOutException();
    }
    // The web container session indicates there is an user, but there's no tracked session: invalidate the session's user
    if (user != null && serviceUser == null) {
        session.removeAttribute("loggedUser");
        throw new LoggedOutException();
    } else {
        // Ensure they match
        final boolean valid = user != null && user.equals(serviceUser);
        if (!valid) {
            session.invalidate();
            throw new AccessDeniedException();
        }
    }
    return user;
}

From source file:org.wso2.carbon.identity.authenticator.saml2.sso.SAML2SSOAuthenticator.java

public void logout() {
    String loggedInUser;/*w  w  w  . j av  a  2  s  .c  o 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 (StringUtils.isNotBlank(loggedInUser)) {
            String logMessage = "'" + loggedInUser + "' logged out at " + date.format(currentTime);

            if (delegatedBy != null) {
                logMessage += " delegated by " + delegatedBy;
            }

            log.info(logMessage);
        }

        session.invalidate();

        if (loggedInUser != null && AUDIT_LOG.isInfoEnabled()) {
            // username in the session is in tenantAware manner
            String tenantAwareUsername = loggedInUser;
            String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();

            String auditInitiator = tenantAwareUsername + UserCoreConstants.TENANT_DOMAIN_COMBINER
                    + tenantDomain;
            String auditData = delegatedBy != null ? "Delegated By : " + delegatedBy : "";

            AUDIT_LOG.info(String.format(SAML2SSOAuthenticatorConstants.AUDIT_MESSAGE, auditInitiator,
                    SAML2SSOAuthenticatorConstants.AUDIT_ACTION_LOGOUT, AUTHENTICATOR_NAME, auditData,
                    SAML2SSOAuthenticatorConstants.AUDIT_RESULT_SUCCESS));
        }
    }
}

From source file:password.pwm.http.filter.RequestInitializationFilter.java

private void checkIfSessionRecycleNeeded(final PwmRequest pwmRequest) throws IOException, ServletException {
    if (!pwmRequest.getPwmSession().getSessionStateBean().isSessionIdRecycleNeeded()) {
        return;//w w w .  j a v  a  2s.  c  o  m
    }

    final boolean recycleEnabled = Boolean
            .parseBoolean(pwmRequest.getConfig().readAppProperty(AppProperty.HTTP_SESSION_RECYCLE_AT_AUTH));

    if (!recycleEnabled) {
        return;
    }
    LOGGER.debug(pwmRequest, "forcing new http session due to authentication");

    final HttpServletRequest req = pwmRequest.getHttpServletRequest();

    // read the old session data
    final HttpSession oldSession = req.getSession(true);
    final int oldMaxInactiveInterval = oldSession.getMaxInactiveInterval();
    final Map<String, Object> sessionAttributes = new HashMap<>();
    final Enumeration oldSessionAttrNames = oldSession.getAttributeNames();
    while (oldSessionAttrNames.hasMoreElements()) {
        final String attrName = (String) oldSessionAttrNames.nextElement();
        sessionAttributes.put(attrName, oldSession.getAttribute(attrName));
    }

    for (final String attrName : sessionAttributes.keySet()) {
        oldSession.removeAttribute(attrName);
    }

    //invalidate the old session
    oldSession.invalidate();

    // make a new session
    final HttpSession newSession = req.getSession(true);

    // write back all the session data
    for (final String attrName : sessionAttributes.keySet()) {
        newSession.setAttribute(attrName, sessionAttributes.get(attrName));
    }

    newSession.setMaxInactiveInterval(oldMaxInactiveInterval);

    pwmRequest.getPwmSession().getSessionStateBean().setSessionIdRecycleNeeded(false);
}

From source file:photosharing.api.bss.LogoutDefinition.java

/** 
 * redirects the user to the logout SSO to destroy the login tokens and login sessions
 * //  w  w w  .ja  v a  2  s .  c o  m
 * @see photosharing.api.conx.APIDefinition#run(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
public void run(HttpServletRequest request, HttpServletResponse response) {
    Configuration config = Configuration.getInstance(request);
    String api = config.getValue(Configuration.BASEURL) + apiUrl;
    try {
        //Invalidating photosharing session on the AppServer and IBM Connections Cloud
        HttpSession session = request.getSession(false);

        if (session != null) {
            logger.info(session.getId() + " is being logged out");

            Request get = Request.Get(api);

            try {
                Executor exec = ExecutorUtil.getExecutor();
                Response apiResponse = exec.execute(get);
                HttpResponse hr = apiResponse.returnResponse();

                /**
                 * Check the status codes and if 200, convert to String
                 */
                int code = hr.getStatusLine().getStatusCode();
                if (code == HttpStatus.SC_OK) {

                } else {
                    logger.log(Level.SEVERE, "Exception Encountered with IBM Connections Cloud Session");
                }

            } catch (IOException e) {
                //Catches Exception Related to a Request
                logger.log(Level.SEVERE, "Exception Encountered");
                response.setHeader("X-Application-Error", className);
                response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            }

            //Indvalidates the User's current session and logs them out
            session.invalidate();
            request.logout();

            //Sets the Status to SC_OK (Http Status Code 200) to indicate a successful logout
            response.setStatus(HttpStatus.SC_NO_CONTENT);
        } else {
            //Something bad has happened
            logger.log(Level.SEVERE, "Invalid Request");
            response.setStatus(HttpStatus.SC_BAD_REQUEST);
        }

    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception Encountered - " + e.toString());

        //Sets the Status to SC_INTERNAL_SERVER_ERROR (Http Status Code 500)
        //Indicates an issue with the Server
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);

    }
}