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:thinwire.render.web.WebServlet.java

private void handlePostEvent(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    HttpSession httpSession = request.getSession();
    ApplicationHolder holder = (ApplicationHolder) httpSession.getAttribute("instance");
    response.setContentType("text/plain; charset=utf-8");
    response.setHeader("Cache-Control", "no-store");
    if (holder == null || holder.app == null)
        return;//  w ww  .  j a va 2 s. com
    holder.app.processActionEvents(request.getReader(), response.getWriter());

    if (holder.app.state == WebApplication.State.TERMINATED) {
        holder.app = null;
        httpSession.invalidate();
    }
}

From source file:org.wso2.carbon.identity.authenticator.krb5.Krb5Authenticator.java

public void logout() throws AuthenticationException {
    String loggedInUser;/*from   w w w  . ja v a  2 s  .  c  om*/
    String delegatedBy;
    String uuid;
    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);
        uuid = nameToUuidMap.get(loggedInUser);
        delegatedBy = (String) session.getAttribute("DELEGATED_BY");
        if (delegatedBy == null && loggedInUser != null) {
            log.info("'" + loggedInUser + "' logged out at " + date.format(currentTime));
        } else if (loggedInUser != null) {
            log.info("'" + loggedInUser + "' logged out at " + date.format(currentTime) + " delegated by "
                    + delegatedBy);
        }
        session.invalidate();
        File tgt = new File(tgtCachePrefix + uuid);
        tgt.delete();
        nameToUuidMap.remove(loggedInUser);
    }
}

From source file:org.openlegacy.mvc.LogoffController.java

@RequestMapping(value = "/logoff", method = RequestMethod.GET)
public String logoff(HttpSession webSession, Model uiModel) throws IOException {

    List<String> trailFiles = new ArrayList<String>();
    for (Session session : sessions) {
        try {//ww  w . j  a  va  2  s.c om
            File trailFile = trailUtil.saveTrail(session);
            if (trailFile != null) {
                trailFiles.add(trailFile.getAbsolutePath());
            }
        } catch (Exception e) {
            logger.warn("Failed to save trail - " + e.getMessage(), e);
        } finally {
            Login loginModule = session.getModule(Login.class);
            if (loginModule != null) {
                loginModule.logoff();
            } else {
                session.disconnect();
            }
        }

    }
    if (invalidateWebSession) {
        webSession.invalidate();
    }
    if (trailFiles.size() > 0) {
        uiModel.addAttribute("trail", trailFiles.get(0));
    }
    return "logoff";
}

From source file:com.neu.edu.servlet.homeController.java

@Override
public ModelAndView handleRequest(HttpServletRequest hsr, HttpServletResponse hsr1) throws Exception {
    HttpSession session = hsr.getSession();
    String action = hsr.getParameter("action");
    ModelAndView mv = new ModelAndView();

    if (action.equals("loginpage")) {
        mv.setViewName("login");
    }//from  www. j a v  a2 s  .c o  m

    else if (action.equals("login")) {
        String uname = hsr.getParameter("username");
        String pass = hsr.getParameter("password");
        Customer c = customerDAo.verifyUser(uname, pass);

        if (c != null) {
            session.setAttribute("customerId", c.getCustomerID());
            session.setAttribute("customerName", c.getName());

            mv.setViewName("index");
        } else {
            mv.addObject("error", "true");
            mv.setViewName("login");
        }
    }

    else if (action.equals("logout")) {
        session.invalidate();
        mv.setViewName("index");
    }

    return mv;
}

From source file:com.curl.orb.servlet.DestroyInstanceServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    super.doPost(request, response);
    Log log = LogFactory.getLog(getClass());
    DestroyInstanceRequest destroyInstanceRequest = (DestroyInstanceRequest) InstanceManagementUtil
            .getRequest(request);//  w w w .j av a 2 s.c o m
    try {
        HttpSession session = request.getSession(false);
        if (session == null)
            throw new InstanceManagementException("Does not exist HttpSession.");
        String objectId = destroyInstanceRequest.getObjectId();
        Object obj = session.getAttribute(objectId);
        // security
        RemoteServiceAnnotationChecker.check(obj.getClass(), environment);
        // remove the object from session
        session.removeAttribute(objectId);

        // kill session
        if (destroyInstanceRequest.getHeader() != null
                && destroyInstanceRequest.getHeader().containsKey(KILL_SESSION)
                && (Boolean) destroyInstanceRequest.getHeader().get(KILL_SESSION)) {
            log.debug("Killed HttpSession:" + session.getId());
            session.invalidate();
        }
        InstanceManagementUtil.setResponse(request, null, null);
        log.debug("Request destroyed");
    }
    // IOException, SerializerException, InstanceManagementException
    catch (Exception e) {
        InstanceManagementUtil.setResponse(request, e, null);
    }
}

From source file:org.eclipse.jetty.nosql.kvs.KeyValueStoreSessionIdManager.java

@Override
protected void doStart() throws Exception {
    log.info("starting...");
    super.doStart();

    _clients = new IKeyValueStoreClient[_poolSize];
    for (int i = 0; i < _poolSize; i++) {
        _clients[i] = createClient();// w ww  .  ja v  a  2  s . c  om
    }
    _pool = new KeyValueStoreClientPool(_clients);

    if (this._defaultExpiry > 0) {
        this._cache = CacheBuilder.newBuilder().expireAfterAccess(this._defaultExpiry, TimeUnit.MILLISECONDS)
                .removalListener(new RemovalListener<Object, HttpSession>() {
                    public void onRemoval(
                            final RemovalNotification<Object, HttpSession> objectObjectRemovalNotification) {
                        HttpSession session = objectObjectRemovalNotification.getValue();
                        if (session != null) {
                            log.debug("Remove from cache " + session.getId());
                            try {
                                if (System.currentTimeMillis()
                                        - session.getLastAccessedTime() > _defaultExpiry) {
                                    log.info("Session timeout, invalidating session " + session.getId());
                                    session.invalidate();
                                }
                            } catch (Exception e) {
                                log.warn("Failed to invalidate session " + session.getId(), e);
                            }
                        }
                    }
                }).build();
    } else {
        this._cache = CacheBuilder.newBuilder().build();
    }

    log.info("started.");
}

From source file:org.codice.ddf.security.servlet.logout.LocalLogoutServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setHeader("Cache-Control", "no-cache, no-store");
    response.setHeader("Pragma", "no-cache");
    response.setContentType("text/html");

    URIBuilder redirectUrlBuilder = null;
    List<NameValuePair> params = new ArrayList<>();

    try {//from w  w w. ja  v  a 2  s . c  o m
        redirectUrlBuilder = new URIBuilder("/logout/logout-response.html");

        HttpSession session = request.getSession();
        if (session != null) {
            SecurityTokenHolder savedToken = (SecurityTokenHolder) session
                    .getAttribute(SecurityConstants.SAML_ASSERTION);
            if (savedToken != null) {
                Subject subject = ThreadContext.getSubject();
                boolean hasSecurityAuditRole = Arrays
                        .stream(System.getProperty("security.audit.roles").split(","))
                        .anyMatch(subject::hasRole);
                if (hasSecurityAuditRole) {
                    SecurityLogger.audit("Subject with admin privileges has logged out", subject);
                }

                savedToken.removeAll();
            }
            session.invalidate();
            deleteJSessionId(response);
        }

        //Check for pki
        if (request.getAttribute("javax.servlet.request.X509Certificate") != null
                && ((X509Certificate[]) request
                        .getAttribute("javax.servlet.request.X509Certificate")).length > 0) {
            params.add(new BasicNameValuePair("msg", "Please close your browser to finish logging out"));
        }

        //Check for basic
        Enumeration authHeaders = request.getHeaders(javax.ws.rs.core.HttpHeaders.AUTHORIZATION);
        while (authHeaders.hasMoreElements()) {
            if (((String) authHeaders.nextElement()).contains("Basic")) {
                params.add(new BasicNameValuePair("msg", "Please close your browser to finish logging out"));
                break;
            }
        }
        redirectUrlBuilder.addParameters(params);
        response.sendRedirect(redirectUrlBuilder.build().toString());
    } catch (URISyntaxException e) {
        LOGGER.debug("Invalid URI", e);
    }
}

From source file:Controllers.CompteController.java

@RequestMapping(value = "connexion", method = RequestMethod.POST)
public ModelAndView connexion(HttpServletRequest request, HttpServletResponse response) throws Exception {

    ModelAndView mv;/*from   w  ww . ja  v  a 2 s  . com*/

    // Rcupration des donnes
    String login = request.getParameter("login");
    String password = request.getParameter("password");

    // Cration de la session
    HttpSession session = request.getSession(true);

    if (session == null) { // Session non cre
        mv = new ModelAndView("connexion");
        mv.addObject("inscriptionMessage", "Veuillez vous connecter pour accder  cette page");
    } else {
        // Attribution de l'id de l'utilisateur qui sera utilis par 
        // le reste de l'application
        session.setAttribute("idUtilisateur", connexionService.connexion(login, password));

        int idPersonne = (int) session.getAttribute("idUtilisateur");
        // Vrification de la connexion
        if (idPersonne != -1) { // Connexion russie
            mv = new ModelAndView("redirect:/mur.htm");
        } else { // Connexion refuse
            session.invalidate();
            mv = new ModelAndView("connexion");
            mv.addObject("inscriptionMessage", "Login ou mot de passe incorrect");
        }
    }
    return mv;
}

From source file:org.wso2.carbon.ui.CarbonUILoginUtil.java

/**
 * //from   w  w  w.  j  a v a2s .com
 * @param authenticator
 * @param request
 * @param response
 * @param session
 * @param authenticated
 * @param contextPath
 * @param indexPageURL
 * @param httpLogin
 * @return
 * @throws IOException
 */
protected static boolean handleLogout(CarbonUIAuthenticator authenticator, HttpServletRequest request,
        HttpServletResponse response, HttpSession session, boolean authenticated, String contextPath,
        String indexPageURL, String httpLogin) throws IOException {
    log.debug("Handling Logout..");
    // Logout the user from the back-end
    try {
        authenticator = (CarbonUIAuthenticator) session
                .getAttribute(CarbonSecuredHttpContext.CARBON_AUTHNETICATOR);
        if (authenticator != null) {
            authenticator.unauthenticate(request);
            log.debug("Backend session invalidated");
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        response.sendRedirect("../admin/login.jsp");
        return false;
    }

    // Only applicable if this is SAML2 based SSO. Complete the logout action after receiving
    // the Logout response.
    if ("true".equals(request.getParameter("logoutcomplete"))) {
        HttpSession currentSession = request.getSession(false);
        if (currentSession != null) {
            // check if current session has expired
            session.removeAttribute(CarbonSecuredHttpContext.LOGGED_USER);
            session.getServletContext().removeAttribute(CarbonSecuredHttpContext.LOGGED_USER);
            try {
                session.invalidate();
            } catch (Exception ignored) { // Ignore exception when
                // invalidating and
                // invalidated session
            }
            log.debug("Frontend session invalidated");
        }
        response.sendRedirect("../../carbon/admin/login.jsp");
        return false;
    }

    if (request.getAttribute("ExternalLogoutPage") != null) {
        HttpSession currentSession = request.getSession(false);
        if (currentSession != null) {
            session.removeAttribute("logged-user");
            session.getServletContext().removeAttribute("logged-user");
            try {
                session.invalidate();
            } catch (Exception ignored) {
            }
            log.debug("Frontend session invalidated");
        }

        response.sendRedirect((String) request.getAttribute("ExternalLogoutPage"));
        return false;
    }

    CarbonSSOSessionManager ssoSessionManager = CarbonSSOSessionManager.getInstance();

    if (!ssoSessionManager.skipSSOSessionInvalidation(request, authenticator)
            && !ssoSessionManager.isSessionValid(request.getSession().getId())) {
        HttpSession currentSession = request.getSession(false);
        if (currentSession != null) {
            // check if current session has expired
            session.removeAttribute(CarbonSecuredHttpContext.LOGGED_USER);
            session.getServletContext().removeAttribute(CarbonSecuredHttpContext.LOGGED_USER);
            try {
                session.invalidate();
                log.debug("SSO session session invalidated ");
            } catch (Exception ignored) { // Ignore exception when
                // Invalidating and invalidated session
                if (log.isDebugEnabled()) {
                    log.debug("Ignore exception when invalidating session", ignored);
                }
            }
        }
        response.sendRedirect("../.." + indexPageURL);
        return false;
    }

    // Memory clean up : remove invalid session from the invalid session list.
    ssoSessionManager.removeInvalidSession(request.getSession().getId());

    // This condition is evaluated when users are logged out in SAML2 based SSO
    if (request.getAttribute("logoutRequest") != null) {
        log.debug("Loging out from SSO session");
        response.sendRedirect("../../carbon/sso-acs/redirect_ajaxprocessor.jsp?logout=true");
        return false;
    }

    HttpSession currentSession = request.getSession(false);
    if (currentSession != null) {
        // Check if current session has expired
        session.removeAttribute(CarbonSecuredHttpContext.LOGGED_USER);
        session.getServletContext().removeAttribute(CarbonSecuredHttpContext.LOGGED_USER);
        try {
            session.invalidate();
            log.debug("Frontend session invalidated");
        } catch (Exception ignored) {
            // Ignore exception when invalidating and invalidated session
        }
    }

    Cookie rmeCookie = new Cookie(CarbonConstants.REMEMBER_ME_COOKE_NAME, null);
    rmeCookie.setPath("/");
    rmeCookie.setSecure(true);
    rmeCookie.setMaxAge(0);
    response.addCookie(rmeCookie);
    response.sendRedirect(contextPath + indexPageURL);
    return false;
}

From source file:com.simplecrud.controller.LogInController.java

/**
 * Process Log In details/*  w w  w. ja v  a 2  s.  c  o m*/
 *
 * @param login
 * @param result
 * @param model
 * @param request
 * @param session
 * @return view
 */
@RequestMapping(value = "/logging")
public ModelAndView validateUser(@Valid @ModelAttribute("LogInForm") ValidateLogIn login, BindingResult result,
        Model model, HttpServletRequest request, HttpSession session) {
    System.out.println(request + "Load  login Page 2");

    //Validate Entered Credentials
    if (result.hasErrors()) {
        //return to login page
        return new ModelAndView(
                "redirect:/login.html?response=Incorrect Username and Password&classerror=has-error");

    } else {

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Object oUser_id;

        try {
            //get user in the db or check if exist
            oUser_id = loginDao.getUserId(username, password);
            //oUser_id Object convert to String to Long
            String sUserId = oUser_id.toString();
            Long lUser_id = Long.parseLong(sUserId);

            session.invalidate();
            HttpSession newSession = request.getSession(); // create session

            System.out.println(newSession + " Load HTTPS Session");
            //Query Success Prepare view (registeredMember.jsp):
            return new ModelAndView("redirect:/registeredmember.html?id=" + lUser_id + "");

        } catch (NoResultException e) {
            System.out.println(e + "Non Entity");
            //Query Failed Prepare view (logInForm.jsp):
            return new ModelAndView(
                    "redirect:/login.html?response=Incorrect Username and Password&classerror=has-error");
        }

    }
}