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:edu.txstate.dmlab.clusteringwiki.web.LoginController.java

@RequestMapping("logout.*")
public String logout(HttpServletRequest request, HttpServletResponse response, Model model) {
    applicationUser.logOut();//from ww  w  .  j  a v a2s.  co  m
    HttpSession session = request.getSession();
    final String testExecutionId = (String) session.getAttribute("executionId");
    if (session != null)
        session.invalidate();
    return testExecutionId == null ? "redirect:index.html" : "redirect:index.html?test=" + testExecutionId;
}

From source file:com.toft.widgets.login.LoginAction.java

/**
 * session?/*from   www .  ja va 2 s  .c o m*/
 */
public String logout() {
    //LicenseListener.logout(this.getRequest().getSession());
    HttpSession session = this.getRequest().getSession();
    if (session != null) {
        session.removeAttribute("userNumber");
        session.invalidate();
    }

    return SUCCESS;
}

From source file:org.hippoecm.repository.PingServlet.java

private void closeHttpSession(HttpServletRequest req) {
    if (req != null) {
        // close open session
        HttpSession httpSession = req.getSession(false);
        if (httpSession != null) {
            httpSession.invalidate();
        }/*www. j a  v  a2s . co m*/
    }
}

From source file:org.alfresco.web.app.servlet.AuthenticationHelper.java

/**
 * Helper to authenticate the current user using the supplied Ticket value.
 * /*from  w w  w.  ja  va 2 s. co m*/
 * @return true if authentication successful, false otherwise.
 */
public static AuthenticationStatus authenticate(ServletContext context, HttpServletRequest httpRequest,
        HttpServletResponse httpResponse, String ticket) throws IOException {
    if (logger.isDebugEnabled())
        logger.debug("Authenticate the current user using the supplied Ticket value.");
    // setup the authentication context
    WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
    AuthenticationService auth = (AuthenticationService) wc.getBean(AUTHENTICATION_SERVICE);
    HttpSession session = httpRequest.getSession();
    try {
        // If we already have a cached user, make sure it is for the right ticket
        SessionUser user = (SessionUser) session.getAttribute(AuthenticationHelper.AUTHENTICATION_USER);
        if (user != null && !user.getTicket().equals(ticket)) {
            if (logger.isDebugEnabled())
                logger.debug("Found a previously-cached user with the wrong identity.");
            session.removeAttribute(AUTHENTICATION_USER);
            if (!Application.inPortalServer()) {
                if (logger.isDebugEnabled())
                    logger.debug("The server is not running in a portal, invalidating session.");
                session.invalidate();
                session = httpRequest.getSession();
            }
            user = null;
        }

        // Validate the ticket and associate it with the session
        auth.validate(ticket);

        if (user == null) {
            if (logger.isDebugEnabled())
                logger.debug("Ticket is valid; caching a new user in the session.");
            setUser(context, httpRequest, auth.getCurrentUserName(), ticket, false);
        } else if (logger.isDebugEnabled())
            logger.debug("Ticket is valid; retaining cached user in session.");
    } catch (AuthenticationException authErr) {
        if (logger.isDebugEnabled())
            logger.debug("An AuthenticationException occured: ", authErr);
        session.removeAttribute(AUTHENTICATION_USER);
        if (!Application.inPortalServer()) {
            if (logger.isDebugEnabled())
                logger.debug("The server is not running in a portal, invalidating session.");
            session.invalidate();
        }
        return AuthenticationStatus.Failure;
    } catch (Throwable e) {
        if (logger.isDebugEnabled())
            logger.debug("Authentication failed due to unexpected error", e);
        // Some other kind of serious failure
        AuthenticationService unprotAuthService = (AuthenticationService) wc.getBean(UNPROTECTED_AUTH_SERVICE);
        unprotAuthService.invalidateTicket(unprotAuthService.getCurrentTicket());
        unprotAuthService.clearCurrentSecurityContext();
        return AuthenticationStatus.Failure;
    }

    // As we are authenticating via a ticket, establish the session locale using request headers rather than web client preferences
    setupThread(context, httpRequest, httpResponse, false);

    return AuthenticationStatus.Success;
}

From source file:com.liferay.portal.action.LoginAction.java

public static void setLoginCookies(HttpServletRequest req, HttpServletResponse res, HttpSession ses,
        long userId, boolean rememberMe) throws PortalException, SystemException, EncryptorException {
    if (GetterUtil.getBoolean(PropsUtil.get(PropsUtil.SESSION_ENABLE_PHISHING_PROTECTION))) {

        // Invalidate the previous session to prevent phishing

        LastPath lastPath = (LastPath) ses.getAttribute(WebKeys.LAST_PATH);

        // GNOMON Gi9: KEEP ANY USER_CARRY ATTRIBUTES (for example shopping cart)
        HashMap userCarryAttributes = getUserCarryAttributes(ses);

        try {/*from  w w w.ja v a  2s.  c  o m*/
            ses.invalidate();
        } catch (Exception e) {
            _log.info("Session has already invalidated");
        }

        ses = req.getSession(true);

        addSessionAttributes(ses, userCarryAttributes);

        if (lastPath != null) {
            ses.setAttribute(WebKeys.LAST_PATH, lastPath);
        }
    }

    // Set cookies

    String domain = PropsUtil.get(PropsUtil.SESSION_COOKIE_DOMAIN);

    User user = UserLocalServiceUtil.getUserById(userId);
    Company company = CompanyLocalServiceUtil.getCompanyById(user.getCompanyId());
    String userIdString = String.valueOf(userId);

    ses.setAttribute("j_username", userIdString);
    ses.setAttribute("j_password", user.getPassword());
    ses.setAttribute("j_remoteuser", userIdString);

    ses.setAttribute(WebKeys.USER_PASSWORD, user.getPassword());

    Cookie idCookie = new Cookie(CookieKeys.ID, UserLocalServiceUtil.encryptUserId(userIdString));

    if (Validator.isNotNull(domain)) {
        idCookie.setDomain(domain);
    }

    idCookie.setPath(StringPool.SLASH);

    Cookie passwordCookie = new Cookie(CookieKeys.PASSWORD,
            Encryptor.encrypt(company.getKeyObj(), user.getPassword()));

    if (Validator.isNotNull(domain)) {
        passwordCookie.setDomain(domain);
    }

    passwordCookie.setPath(StringPool.SLASH);

    int loginMaxAge = GetterUtil.getInteger(PropsUtil.get(PropsUtil.COMPANY_SECURITY_AUTO_LOGIN_MAX_AGE),
            CookieKeys.MAX_AGE);

    if (GetterUtil.getBoolean(PropsUtil.get(PropsUtil.SESSION_DISABLED))) {

        rememberMe = true;
    }

    if (rememberMe) {
        idCookie.setMaxAge(loginMaxAge);
        passwordCookie.setMaxAge(loginMaxAge);
    } else {
        idCookie.setMaxAge(0);
        passwordCookie.setMaxAge(0);
    }

    Cookie loginCookie = new Cookie(CookieKeys.LOGIN, user.getLogin());

    if (Validator.isNotNull(domain)) {
        loginCookie.setDomain(domain);
    }

    loginCookie.setPath(StringPool.SLASH);
    loginCookie.setMaxAge(loginMaxAge);

    Cookie screenNameCookie = new Cookie(CookieKeys.SCREEN_NAME,
            Encryptor.encrypt(company.getKeyObj(), user.getScreenName()));

    if (Validator.isNotNull(domain)) {
        screenNameCookie.setDomain(domain);
    }

    screenNameCookie.setPath(StringPool.SLASH);
    screenNameCookie.setMaxAge(loginMaxAge);

    CookieKeys.addCookie(res, idCookie);
    CookieKeys.addCookie(res, passwordCookie);
    CookieKeys.addCookie(res, loginCookie);
    CookieKeys.addCookie(res, screenNameCookie);

    //add entry to user tracking if needed
    boolean trackUser = GetterUtil.getBoolean(PropsUtil.get(user.getCompanyId(), "gn.user.tracking.enabled"),
            false);
    if (trackUser) {
        GnUserTracking track = new GnUserTracking();
        track.setCompanyId(user.getCompanyId());
        track.setUserId(user.getUserId());
        track.setLoginDate(new Date());
        String fromIp = req.getHeader("X-Forwarded-For");
        if (Validator.isNull(fromIp))
            fromIp = req.getRemoteAddr() + (Validator.isNotNull(req.getRemoteHost())
                    && !req.getRemoteAddr().equals(req.getRemoteHost()) ? "( " + req.getRemoteHost() + " )"
                            : "");

        track.setFromIp(fromIp);
        GnPersistenceService.getInstance(null).createObject(track);
    }
    EventsService.getInstance().createEvent(user, "PortalAuth",
            "User " + user.getScreenName() + " has logged in " + req.getServerName(), "loginaction", null);
}

From source file:edu.emory.cci.aiw.cvrg.eureka.servlet.filter.UserFilter.java

@Override
public void doFilter(ServletRequest inRequest, ServletResponse inResponse, FilterChain inFilterChain)
        throws IOException, ServletException {

    HttpServletRequest servletRequest = (HttpServletRequest) inRequest;
    HttpServletResponse servletResponse = (HttpServletResponse) inResponse;
    String remoteUser = servletRequest.getRemoteUser();

    inRequest.setAttribute(RequestAttributes.User_Webapp_URL, this.properties.getUserWebappUrl());
    inRequest.setAttribute(RequestAttributes.User_Service_URL, this.properties.getUserServiceUrl());

    Boolean userIsActive = true;// ww  w  . java  2  s .c  o  m
    if (!StringUtils.isEmpty(remoteUser)) {
        try {
            HttpSession session = servletRequest.getSession(false);
            if (session != null) {
                User user = this.inUserClient.getMe();
                userIsActive = this.inUserClient.getMe().isActive();
                if (!userIsActive) {
                    session.invalidate();
                    sendForbiddenError(servletResponse, servletRequest, true);
                } else {
                    inRequest.setAttribute(RequestAttributes.USER, user);
                    inRequest.setAttribute(RequestAttributes.USER_IS_ACTIVATED, userIsActive);
                    inFilterChain.doFilter(inRequest, inResponse);
                }
            } else {
                goHome(servletRequest, servletResponse);
            }
        } catch (ClientException ex) {
            if (null != ex.getResponseStatus()) {
                switch (ex.getResponseStatus()) {
                case FORBIDDEN: {
                    HttpSession session = servletRequest.getSession(false);
                    if (session != null) {
                        session.invalidate();
                    }
                    sendForbiddenError(servletResponse, servletRequest, false);
                    break;
                }
                case UNAUTHORIZED: {
                    HttpSession session = servletRequest.getSession(false);
                    if (session != null) {
                        session.invalidate();
                    }
                    goHome(servletRequest, servletResponse);
                    break;
                }
                default:
                    throw new ServletException("Error getting user " + servletRequest.getRemoteUser(), ex);
                }
            }
        }
    } else {
        inFilterChain.doFilter(inRequest, inResponse);
    }
}

From source file:ua.aits.Carpath.controller.SystemController.java

@RequestMapping(value = { "/system/do/logout.do", "/archive/do/logout.do/", "/Carpath/system/do/logout.do",
        "/Carpath/archive/do/logout.do/" })
public ModelAndView logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
    request.setCharacterEncoding("UTF-8");
    HttpSession session = request.getSession(false);
    if (session != null) {
        session.invalidate();
    }//from w w w.  ja v  a  2  s.c  o m
    return new ModelAndView("redirect:" + "/en/login");
}

From source file:br.ufg.calendario.components.UsuarioBean.java

public String encerraSessao() {
    HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext()
            .getSession(false);//  w  w w .  j  a  va2s  . c o  m
    session.invalidate();
    return "/views/home?faces-redirect=true";
}

From source file:de.itsvs.cwtrpc.security.AbstractRpcProcessingFilter.java

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

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

From source file:org.opendaylight.controller.web.DaylightWebAdmin.java

@RequestMapping(value = "/users/password/{username}", method = RequestMethod.POST)
@ResponseBody/*w ww . ja va2  s  .c om*/
public Status changePassword(@PathVariable("username") String username, HttpServletRequest request,
        @RequestParam(value = "currentPassword", required = false) String currentPassword,
        @RequestParam("newPassword") String newPassword) {
    IUserManager userManager = (IUserManager) ServiceHelper.getGlobalInstance(IUserManager.class, this);
    if (userManager == null) {
        return new Status(StatusCode.NOSERVICE, "User Manager unavailable");
    }

    Status status;
    String requestingUser = request.getUserPrincipal().getName();

    //changing own password
    if (requestingUser.equals(username)) {
        status = userManager.changeLocalUserPassword(username, currentPassword, newPassword);
        //enforce the user to re-login with new password
        if (status.isSuccess() && !newPassword.equals(currentPassword)) {
            userManager.userLogout(username);
            HttpSession session = request.getSession(false);
            if (session != null) {
                session.invalidate();
            }
        }

        //admin level user resetting other's password
    } else if (authorize(userManager, UserLevel.NETWORKADMIN, request)) {

        //Since User Manager doesn't have an unprotected password change API,
        //we re-create the user with the new password (and current roles).
        List<String> roles = userManager.getUserRoles(username);
        UserConfig newConfig = new UserConfig(username, newPassword, roles);

        //validate before removing existing config, so we don't remove but fail to add
        status = newConfig.validate();
        if (!status.isSuccess()) {
            return status;
        }

        userManager.userLogout(username);
        status = userManager.removeLocalUser(username);
        if (!status.isSuccess()) {
            return status;
        }
        if (userManager.addLocalUser(newConfig).isSuccess()) {
            status = new Status(StatusCode.SUCCESS, "Password for user " + username + " reset successfully.");
        } else {
            //unexpected
            status = new Status(StatusCode.INTERNALERROR,
                    "Failed resetting password for user " + username + ". User is now removed.");
        }

        //unauthorized
    } else {
        status = new Status(StatusCode.UNAUTHORIZED, "Operation not permitted");
    }

    if (status.isSuccess()) {
        DaylightWebUtil.auditlog("User", request.getUserPrincipal().getName(), "changed password for",
                username);
    }
    return status;
}