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:at.gv.egovernment.moa.id.configuration.filter.AuthenticationFilter.java

public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterchain)
        throws IOException, ServletException {

    HttpServletRequest httpServletRequest = (HttpServletRequest) req;
    HttpServletResponse httpServletResponse = (HttpServletResponse) resp;

    HttpSession session = httpServletRequest.getSession();

    Object authuserobj = session.getAttribute(Constants.SESSION_AUTH);
    AuthenticatedUser authuser = (AuthenticatedUser) authuserobj;

    String requestURL = WebAppUtil.getRequestURLWithParameters(httpServletRequest, true);

    log.trace("Request URL: " + requestURL);

    AuthenticationManager authManager = AuthenticationManager.getInstance();
    if (!authManager.isActiveUser(authuser)) {
        //user is not active anymore. Invalidate session and reauthenticate user
        String authID = (String) session.getAttribute(Constants.SESSION_PVP2REQUESTID);
        session.invalidate();
        authuser = null;//from  ww w .jav  a  2s . c o  m

        //TODO: set infotext

        session = httpServletRequest.getSession(true);
        session.setAttribute(Constants.SESSION_PVP2REQUESTID, authID);
    }

    if (authuser == null && !this.isExcluded(requestURL)) {

        if (config.isLoginDeaktivated()) {
            //add dummy Daten
            log.warn("Authentication is deaktivated. Dummy authentication-information are used!");

            if (authuser == null) {
                int sessionTimeOut = session.getMaxInactiveInterval();
                Date sessionExpired = new Date(
                        new Date().getTime() + (sessionTimeOut * Constants.ONE_MINUTE_IN_MILLIS));

                authuser = AuthenticatedUser.generateDefaultUser(sessionExpired);
                authManager.setActiveUser(authuser);

                //authuser = new AuthenticatedUser(1, "Max", "TestUser", true, false);
                httpServletRequest.getSession().setAttribute(Constants.SESSION_AUTH, authuser);
            }

            if (MiscUtil.isNotEmpty(getAuthenticatedPage())) {
                if (loginPageForward) {
                    log.debug("Authenticated page is set. Forwarding to \"" + getAuthenticatedPage() + "\".");
                    RequestDispatcher dispatcher = req.getRequestDispatcher(getAuthenticatedPage());
                    dispatcher.forward(httpServletRequest, httpServletResponse);
                } else {
                    log.debug("Authenticated page is set. Redirecting to \"" + getAuthenticatedPage() + "\".");
                    httpServletResponse
                            .sendRedirect(httpServletResponse.encodeRedirectURL(getAuthenticatedPage()));
                }
                return;
            }

        } else {
            if (MiscUtil.isNotEmpty(getAuthenticatedPage())) {
                log.debug(
                        "Unable to find authentication data. Authenticated page is given so there is no need to save original request url. "
                                + (loginPageForward ? "Forwarding" : "Redirecting") + " to login page \""
                                + loginPage + "\".");

            } else {
                log.debug("Unable to find authentication data. Storing request url and "
                        + (loginPageForward ? "forwarding" : "redirecting") + " to login page \"" + loginPage
                        + "\".");
                session.setAttribute(STORED_REQUEST_URL_ID, requestURL);

            }

            if (loginPageForward) {
                RequestDispatcher dispatcher = req.getRequestDispatcher(loginPage);
                dispatcher.forward(httpServletRequest, httpServletResponse);
                return;

            } else {
                httpServletResponse.sendRedirect(httpServletResponse.encodeRedirectURL(loginPage));
                return;

            }
        }

    } else {
        try {
            filterchain.doFilter(req, resp);

        } catch (Exception e) {

            //String redirectURL = "./index.action";
            //HttpServletResponse httpResp = (HttpServletResponse) resp;
            //redirectURL = httpResp.encodeRedirectURL(redirectURL);
            //resp.setContentType("text/html");
            //((HttpServletResponse) resp).setStatus(302);
            //httpResp.addHeader("Location", redirectURL);
            //log.warn("A Filter Error occurs -> Redirect to Login-Form");
        }
    }
}

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

private IdentitySwapHelper getIdentitySwapDataAndInvalidateSession(final HttpServletRequest request,
        final org.springframework.security.core.Authentication originalAuth) {
    IdentitySwapHelper identitySwapHelper = null;
    try {/*from   www  .  ja  v a  2  s . com*/
        HttpSession s = request.getSession(false);
        if (s != null) {
            final IPerson person = personManager.getPerson(request);
            identitySwapHelper = new IdentitySwapHelper(s, person.getName());
            if (identitySwapHelper.isSwapRequest()) {
                identitySwapHelper.setOriginalAuthenticationForSwap(originalAuth);
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Invalidating the impersonated session in un-swapping.");
            }
            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);
        }
    }
    return identitySwapHelper;
}

From source file:com.kgmp.mfds.controller.AdminController.java

@RequestMapping(value = "/AdminLogOut.do", method = RequestMethod.GET)
public String logOut(HttpSession session) {
    session.invalidate();
    return "/admin/Admin_Login";
}

From source file:org.jbpm.designer.filter.DesignerBasicAuthSecurityFilter.java

@Override
public void doFilter(ServletRequest _request, ServletResponse _response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) _request;
    HttpServletResponse response = (HttpServletResponse) _response;
    HttpSession session = request.getSession(false);
    User user = this.authenticationService.getUser();

    // For HTTP OPTIONS verb/method reply with ACCEPTED status code -- per CORS handshake
    if (request.getMethod().equals("OPTIONS")) {
        response.setStatus(HttpServletResponse.SC_ACCEPTED);
        return;/*w w w  .  j  a  va 2s.c  om*/
    }

    try {
        if (user == null) {
            if (this.authenticate(request)) {
                chain.doFilter(request, response);
                if (response.isCommitted()) {
                    this.authenticationService.logout();
                }
            } else {
                this.challengeClient(request, response);
            }
        } else {
            chain.doFilter(request, response);
        }
    } finally {
        if (session == null) {
            session = request.getSession(false);
            if (session != null) {
                session.invalidate();
            }
        }
    }
}

From source file:com.skilrock.lms.web.loginMgmt.RolesInterceptor.java

public boolean isSessionValid(HttpSession session) {
    HttpSession sessionNew = null;//from   w w  w  . ja  v a  2  s  .c  om
    ServletContext sc = ServletActionContext.getServletContext();
    Map currentUserSessionMap = (Map) sc.getAttribute("LOGGED_IN_USERS");
    UserInfoBean userBean = (UserInfoBean) session.getAttribute("USER_INFO");
    if (userBean == null) {

        return false;
    }
    if (currentUserSessionMap != null && userBean != null) {
        sessionNew = (HttpSession) currentUserSessionMap.get(userBean.getUserName());
    }
    // logger.debug("In Else If New is --"+sessionNew+" Session Current
    // --"+session);
    // logger.debug("The User in Map are"+currentUserSessionMap );
    if (sessionNew != null) {
        if (!sessionNew.equals(session)) {
            session.removeAttribute("USER_INFO");
            session.invalidate();
            session = null;
            return false;
        }
    }
    return true;

}

From source file:com.sct.descubriendoturuta.controller.HomeController.java

@RequestMapping(value = "/", method = RequestMethod.GET)
public String index(HttpSession session, Map<String, Object> map) {

    /*/* www. j  a  v a  2  s . c o m*/
     * Se verifica que exista la secin. de ser as se carga el perfil del
     * usuario.
     */
    if (session.getAttribute(SESSION_FACEBOOK_ID) != null && session.getAttribute(SESSION_FACEBOOK_ID) != "") {

        final String facebookId = (String) session.getAttribute(SESSION_FACEBOOK_ID);

        final String nombre = (String) session.getAttribute(SESSION_NOMBRE_USUARIO);

        Usuario u = usuarioService.buscarFacebookId(facebookId);

        if (u != null) {

            map.put("facebookId", facebookId);
            map.put("nombre", nombre);

        } else {
            // Se limpia la sesin.
            session.invalidate();
        }

    }

    List<Ruta> rutas = usuarioService.obtenerRutasPopulares();
    List<Usuario> usuarios = insigniaService.obtenerUsuariosPopulares();

    map.put("rutasPopulares", rutas);
    map.put("usuariosPopulares", usuarios);

    return "index";
}

From source file:com.poscoict.license.service.BoardService.java

public String checkLogin(String text, String password, HttpSession session, HttpServletRequest request) {
    logger.info("_______checkLogin: " + text);
    String url = "redirect:/board";
    int check = 0;

    session.invalidate();
    session = request.getSession();//from ww w.j  a  v  a  2 s  . c om

    if ((text.trim() != "") && (password.trim() != "")) {
        check = userDao.loginCheck(text.trim(), password.trim());
        if (check == 1) {
            UserInfo user = userDao.get(text.trim());
            session.setAttribute("USER_NO", user.getUSER_NO());
            session.setAttribute("USER_NAME", user.getUSER_NAME());
            session.setAttribute("USER_PASSWORD", user.getUSER_PASSWORD());
            session.setAttribute("USER_TYPE", user.getUSER_TYPE());
            if (user.getUSER_TYPE().equals("D")) {
                session.setAttribute("SUPER_USER", true);
            } else if (user.getUSER_TYPE().equals("S")) {
                session.setAttribute("SUBCONTRACT", true);
            } else if (user.getUSER_TYPE().equals("U")) {
                session.setAttribute("PUBLIC_USER", true);
            } else {
                // guest ? 
                session.setAttribute("GUEST_USER", true);
            }

            if (!user.getUSER_TYPE().equals("G") && user.getUSER_NO().equals(user.getUSER_PASSWORD())) {
                session.setAttribute("changePassword", true);
            }
            logger.info("checkLogin: " + text + " USER_TYPE " + user.getUSER_TYPE());
        } else {
            url = "redirect:/popup/error.jsp";

            //
            UserInfo user = userDao.get(text.trim());
            logger.info("@@ failed USER_NAME : " + session.getAttribute("USER_NAME"));
            logger.info("@@ failed getUSER_NAME : " + user.getUSER_NAME());

            session.setAttribute("msg", "?    .");
            session.setAttribute("send", "/index.jsp");
            logger.info("checkLogin: " + text + " ?    .");
        }
    } else {
        url = "redirect:/popup/error.jsp";
        session.setAttribute("msg", "?  .");
        session.setAttribute("send", "/index.jsp");
    }
    logger.info("checkLogin: success " + text);
    return url;
}

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

private void checkAndInitSessionState(final HttpServletRequest request) throws PwmUnrecoverableException {
    final ContextManager contextManager = ContextManager.getContextManager(request.getSession());
    final PwmApplication pwmApplication = contextManager.getPwmApplication();

    { // destroy any outdated sessions
        final HttpSession httpSession = request.getSession(false);
        if (httpSession != null) {
            final String sessionPwmAppNonce = (String) httpSession
                    .getAttribute(PwmConstants.SESSION_ATTR_PWM_APP_NONCE);
            if (sessionPwmAppNonce == null || !sessionPwmAppNonce.equals(pwmApplication.getRuntimeNonce())) {
                LOGGER.debug("invalidating http session created with non-current servlet context");
                httpSession.invalidate();
            }/* w  w w  .  j  a v a 2 s  .c  o m*/
        }
    }

    { // handle pwmSession init and assignment.
        final HttpSession httpSession = request.getSession();
        if (httpSession.getAttribute(PwmConstants.SESSION_ATTR_PWM_SESSION) == null) {
            final PwmSession pwmSession = PwmSession.createPwmSession(pwmApplication);
            PwmSessionWrapper.sessionMerge(pwmApplication, pwmSession, httpSession);
        }
    }

}

From source file:net.shopxx.controller.shop.OAuthController.java

/**
 * ?session?//from www .j a v a 2  s  . c  o m
 * @param session
 * @param request
 * @param response
 * @param member
 */
private void saveSession(HttpSession session, HttpServletRequest request, HttpServletResponse response,
        Member member) {
    Cart cart = cartService.getCurrent();
    if (cart != null) {
        if (cart.getMember() == null) {
            cartService.merge(member, cart);
            WebUtils.removeCookie(request, response, Cart.ID_COOKIE_NAME);
            WebUtils.removeCookie(request, response, Cart.KEY_COOKIE_NAME);
        }
    }
    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:nl.b3p.gis.viewer.services.GisPrincipal.java

public static GisPrincipal getGisPrincipal(HttpServletRequest request, boolean flushCache) {
    HttpSession session = request.getSession();

    /* Controleren of er al een andere gebruiker is ingelogd */
    Principal user = request.getUserPrincipal();
    if (!(user instanceof GisPrincipal && request instanceof SecurityRequestWrapper)) {
        return null;
    }//from  w  ww  .j a  va  2s .  c  o m

    String gpCode = null;
    String gpUsername = HibernateUtil.ANONYMOUS_USER;
    String gpPassword = null;

    GisPrincipal gp = (GisPrincipal) user;
    if (gp != null) {
        gpCode = gp.getCode();
        gpUsername = gp.getName();
        gpPassword = gp.getPassword();
    }

    String appCode = request.getParameter(BaseGisAction.APP_AUTH);

    Applicatie app = null;
    if (appCode != null && appCode.length() > 0) {
        app = KaartSelectieUtil.getApplicatie(appCode);
    }

    //        Boolean loginForm = (Boolean) session.getAttribute("loginForm"); // remove this
    //        if (loginForm == null) {
    //            loginForm = false;
    //        }

    /* Applicatie geen gebruikerscode en niet via formulier gekomen */
    //        if (app != null && app.getGebruikersCode() == null && !loginForm) { // this can probaly be removed
    //            session.invalidate();
    //
    //            log.debug("Applicatie zonder gebruikerscode. Terug naar login form.");
    //
    //            return null;
    //        }

    /* Gebruikerscode verschilt met huidige inlog. Automatisch inloggen. */
    if (gp != null && app != null && app.getGebruikersCode() != null
            && !app.getGebruikersCode().equals(gp.getCode())) {
        A11YResult a11yResult = (A11YResult) session.getAttribute("a11yResult");

        session.invalidate();

        gp = null;
        gpCode = app.getGebruikersCode();
        gpUsername = HibernateUtil.ANONYMOUS_USER;
        gpPassword = null;

        SecurityRequestWrapper srw = (SecurityRequestWrapper) request;

        gp = (GisPrincipal) GisSecurityRealm.authenticate(gpUsername, gpPassword, gpCode);
        srw.setUserPrincipal(gp);

        /* Fix zodat gekozen startlocatie ook werkt voor nieuwe sessie als er als andere
         * user wordt ingelogd. */
        if (a11yResult != null) {
            HttpSession newSession = request.getSession(true);
            newSession.setAttribute("a11yResult", a11yResult);
        }

        log.debug("Gebruikerscode verschilt. Automatisch ingelogd met nieuwe gebruiker.");
    }

    /* Applicatie geen gebruikerscode. Inloggen met gegevens van formulier. */
    if (app != null && app.getGebruikersCode() == null) { // check how this works
        SecurityRequestWrapper srw = (SecurityRequestWrapper) request;

        gp = (GisPrincipal) GisSecurityRealm.authenticate(gpUsername, gpPassword, gpCode);
        srw.setUserPrincipal(gp);

        log.debug("Applicatie zonder gebruikerscode. Nu ingelogd via formulier.");
    }

    return gp;
}