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:de.suse.swamp.modules.actions.LoginActions.java

public void doLogoutuser(RunData data, Context context) throws Exception {
    User user = data.getUser();/* ww w .  j a  va  2 s.  c  om*/

    if (!TurbineSecurity.isAnonymousUser(user)) {
        // Make sure that the user has really logged in...
        if (!user.hasLoggedIn()) {
            Logger.ERROR("Trying to logout a not-logged-in User! (" + user.getName() + ")");
            return;
        }
        user.setHasLoggedIn(Boolean.FALSE);
    }

    Configuration conf = Turbine.getConfiguration();
    data.setMessage(conf.getString(TurbineConstants.LOGOUT_MESSAGE));

    // This will cause the acl to be removed from the session in the Turbine servlet code.
    data.setACL(null);

    // Retrieve an anonymous user.
    data.setUser(TurbineSecurity.getAnonymousUser());

    // In the event that the current screen or related navigations
    // require acl info, we cannot wait for Turbine to handle
    // regenerating acl.
    data.getSession().removeAttribute(AccessControlList.SESSION_KEY);
    data.save();

    HttpSession session = data.getSession();
    session.invalidate();
    data.setUser(TurbineSecurity.getAnonymousUser());
    String loginScreen = Turbine.getConfiguration().getString("template.login");
    data.setScreenTemplate(loginScreen);
    Logger.LOG(user.getName() + " has logged out.");

    // Check for XML-Output for external scripts
    if (data.getParameters().containsKey("xmlresponse")
            && data.getParameters().get("xmlresponse").equals("true")) {
        ExternalActions.doSendXMLOutput(data, "0", "Your are logged out");
    }

}

From source file:ph.fingra.statisticsweb.controller.LoginLogoutController.java

@RequestMapping(value = "logout", method = RequestMethod.GET)
public void logout(HttpSession session) {
    FingraphUser userDetails = (FingraphUser) session.getAttribute("userLoginInfo");

    logger.debug("Welcome logout! {}, {}", session.getId(), userDetails.getUsername());

    session.invalidate();
}

From source file:com.havoc.hotel.controller.HomeController.java

@RequestMapping(method = RequestMethod.GET, value = "logout")
public String Logout(HttpServletRequest req, HttpServletResponse resp) {
    HttpSession session = req.getSession(false);
    String checking = (String) session.getAttribute("username");
    if (checking == null) {
        return "redirect:/?logout=false";
    } else {/*from   w w w . j a v  a2s . c  o  m*/
        session.invalidate();
        return "redirect:/";
    }
}

From source file:edu.emory.cci.aiw.cvrg.eureka.servlet.filter.HaveUserRecordFilter.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();
    if (!StringUtils.isEmpty(remoteUser)) {
        try {//from  ww w.j  ava2  s .c  o  m
            User user = this.servicesClient.getMe();
            if (!user.isActive()) {
                HttpSession session = servletRequest.getSession(false);
                if (session != null) {
                    session.invalidate();
                }
                sendForbiddenError(servletResponse, servletRequest, true);
            } else {
                inRequest.setAttribute("user", user);
                inFilterChain.doFilter(inRequest, inResponse);
            }
        } catch (ClientException ex) {
            if (Status.FORBIDDEN.equals(ex.getResponseStatus())) {
                HttpSession session = servletRequest.getSession(false);
                if (session != null) {
                    session.invalidate();
                }
                sendForbiddenError(servletResponse, servletRequest, false);
            } else if (Status.UNAUTHORIZED.equals(ex.getResponseStatus())) {
                HttpSession session = servletRequest.getSession(false);
                if (session != null) {
                    session.invalidate();
                }
                servletResponse.sendRedirect(servletRequest.getContextPath() + "/logout?goHome=true");
            } else {
                throw new ServletException("Error getting user " + servletRequest.getRemoteUser(), ex);
            }
        }
    } else {
        inFilterChain.doFilter(inRequest, inResponse);
    }
}

From source file:com.havoc.hotel.admin.controller.CheckinController.java

@RequestMapping(method = RequestMethod.GET, value = "/logout")
public String Logout(HttpServletRequest req, HttpServletResponse resp) {
    HttpSession session = req.getSession(false);
    String checking = (String) session.getAttribute("username");
    if (checking == null) {
        return "redirect:/?logout=false";
    } else {/*from w w  w  . j  av  a2s .co m*/
        session.invalidate();
        return "redirect:/admin";
    }
}

From source file:org.frat.common.security.BaseSecurityContext.java

/**
 * ./* ww  w  .j  a va2s . com*/
 * 
 * @param username
 */
public static void kickOutUnLogin() {
    try {
        WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
        ServletContext servletContext = webApplicationContext.getServletContext();

        // applicationHashSet?session
        @SuppressWarnings("unchecked")
        HashSet<HttpSession> sessions = (HashSet<HttpSession>) servletContext.getAttribute("loginSessions");
        List<HttpSession> sessionList = new ArrayList<HttpSession>();
        if (StringUtil.isObjNotNull(sessions)) {
            for (HttpSession session : sessions) {
                SysUserDto user = (SysUserDto) session.getAttribute("shiro.user");
                if (null != session && StringUtil.isObjNull(user)) {
                    // LOGGER.debug("getLastAccessedTime="+ new
                    // Date(session.getLastAccessedTime()));
                    // LOGGER.debug("now="+ new Date());
                    int diffTime = DateUtil.diffTime(new Date(), new Date(session.getLastAccessedTime()));
                    // LOGGER.debug("diffTime="+diffTime);
                    if (diffTime > 300) {
                        sessionList.add(session);
                    }
                }
            }
            for (HttpSession session : sessionList) {
                session.invalidate();
                LOGGER.debug("success kick out UnLogin session [" + session.getId() + "]");
            }
        }
    } catch (Exception e) {
        LOGGER.error("");
        LOGGER.error(StackTraceUtil.getStackTrace(e));
    }

}

From source file:br.com.everson.clei.springmvc.controller.ContasController.java

@RequestMapping("sairDaConta")
public String sair(HttpServletRequest hsr, HttpSession hs, Model m, Operacao o) {
    hs.invalidate();
    return "redirect:inicio";
}

From source file:com.hiperium.web.restful.authentication.AuthenticationREST.java

/**
 * Used by JavaScript in the presentation layer to authenticate the user.
 *
 * @param credentialsDTO/*from   www . j ava  2  s.  c  om*/
 * @return
 * @throws InformationException
 * @throws PropertyValidationException
 */
@POST
@Produces(MediaType.TEXT_PLAIN)
public Response login(@NotNull UserCredentialDTO credentialsDTO)
        throws InformationException, PropertyValidationException {
    LOGGER.debug("login - BEGIN");

    // Validates that the username property was not set for security reasons
    if (StringUtils.isNotBlank(credentialsDTO.getUsername())) {
        throw InformationException.generate(EnumI18N.SECURITY, EnumInformationException.USER_NOT_FOUND,
                Locale.getDefault());
    }

    // Validate object parameter
    Set<ConstraintViolation<UserCredentialDTO>> violations = this.validator.validate(credentialsDTO);
    if (!violations.isEmpty()) {
        throw new PropertyValidationException(new HashSet<ConstraintViolation<?>>(violations));
    }

    // Validates the credentials
    String urlNavigation = EnumNavigation.ERROR.getURL();
    if (this.securityBusinessDelegate.getAuthenticationBO().validateUserCredentials(credentialsDTO.getEmail(),
            credentialsDTO.getPassword())) {

        // Invalidate the actual session and creates a new one
        HttpSession sessionOld = this.servletRequest.getSession(false);
        sessionOld.invalidate();
        HttpSession sessionNew = this.servletRequest.getSession(true);

        // Creates a session register with a new HTTP session
        String userAgent = this.servletRequest.getHeader("User-Agent");
        String remoteIpAddress = this.servletRequest.getRemoteAddr();
        SessionRegisterDTO sessionRegisterDTO = this.securityBusinessDelegate.getAuthenticationBO()
                .userAuthentication(credentialsDTO.getEmail(), userAgent, remoteIpAddress, false,
                        sessionNew.getId());

        // Sets the application language based in the user language
        LanguageBean languageBean = (LanguageBean) sessionNew.getAttribute(LanguageBean.BEAN_NAME);
        UserSessionBean userSessionBean = (UserSessionBean) sessionNew.getAttribute(UserSessionBean.BEAN_NAME);
        languageBean.setLocale(new Locale(sessionRegisterDTO.getLocale().getLanguage()));

        // Verify if user needs to change the password
        if (this.securityBusinessDelegate.getAuthenticationBO().userNeedToChangePasswd(sessionNew.getId())) {
            urlNavigation = EnumNavigation.UPDATE_PASSWORD.getURL();
            userSessionBean.getSessionInformationDTO()
                    .setBreadCrumb(new BreadCrumbDTO(0,
                            Resources.getResourceBundle(EnumI18N.SECURITY, languageBean.getLocale())
                                    .getString("passwordChange"),
                            urlNavigation));
        } else {
            urlNavigation = EnumNavigation.HOME_SELECTION.getURL();
            userSessionBean.getSessionInformationDTO()
                    .setBreadCrumb(new BreadCrumbDTO(0,
                            Resources.getResourceBundle(EnumI18N.SECURITY, languageBean.getLocale())
                                    .getString("homeSelection"),
                            urlNavigation));
        }
        // Sets the absolute session timeout.
        sessionNew.setAttribute(NavigationControl.SESSION_TIME_LABEL, System.currentTimeMillis());
    } else {
        throw InformationException.generate(EnumI18N.SECURITY, EnumInformationException.USER_NOT_FOUND,
                Locale.getDefault());
    }
    LOGGER.debug("login - END");
    return Response.status(Status.OK).entity(urlNavigation).type(MediaType.TEXT_PLAIN).build();
}

From source file:org.asqatasun.webapp.controller.LoginController.java

/**
 * // ww w  . j a  v a2  s .  co m
 * @param request 
 */
private void logoutCurrentUser(HttpServletRequest request) {
    SecurityContextHolder.clearContext();
    HttpSession session = request.getSession(false);
    if (session != null) {
        session.invalidate();
    }
}

From source file:org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler.java

/**
 * Requires the request to be passed in.
 *
 * @param request from which to obtain a HTTP session (cannot be null)
 * @param response not used (can be <code>null</code>)
 * @param authentication not used (can be <code>null</code>)
 *///from w  w w.j a  va  2s .c om
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
    Assert.notNull(request, "HttpServletRequest required");
    if (invalidateHttpSession) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            logger.debug("Invalidating session: " + session.getId());
            session.invalidate();
        }
    }

    if (clearAuthentication) {
        SecurityContext context = SecurityContextHolder.getContext();
        context.setAuthentication(null);
    }

    SecurityContextHolder.clearContext();
}