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:org.rhq.enterprise.gui.authentication.LogoutAction.java

/**
 * log a user out of the system./*from www  . j  av a  2s .co m*/
 */
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Log log = LogFactory.getLog(LogoutAction.class.getName());

    ServletContext ctx = getServlet().getServletContext();
    SubjectManagerLocal authBoss = LookupUtil.getSubjectManager();
    Integer sessionId = RequestUtils.getSessionId(request);
    authBoss.logout(sessionId.intValue());

    HttpSession session = request.getSession();

    clearSubjectPreferences(session);

    session.removeAttribute(Constants.USER_PARAM);
    SessionUtils.setWebUser(session, null);
    session.invalidate();

    return mapping.findForward(RetCodeConstants.SUCCESS_URL);
}

From source file:org.wso2.carbon.la.restapi.LoginLogoutApiV10.java

/**
 * Logout./*from   w  w  w.java2s  .c o m*/
 */
@POST
@Path("/logout")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response logout() {
    HttpSession session = httpServletRequest.getSession();
    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    if (session != null) {
        session.invalidate();
    }
    return Response.status(Response.Status.OK).entity("User logged out: " + carbonContext.getUsername())
            .build();
}

From source file:com.envision.envservice.filter.LoginFilter.java

/**
 * ?//from  w  w w. ja v a2s. co  m
 */
private boolean loginCheck(HttpServletRequest request, HttpServletResponse response) throws IOException {
    boolean flag = true;

    HttpSession session = request.getSession(false);
    if (request.getRequestURI().endsWith(Constants.URL_LOGIN)) {
        if (session != null) {
            session.invalidate();
        }
    } else {
        // ?
        if (session != null) {
            UserBo user = (UserBo) session.getAttribute(Constants.SESSION_USER);
            if (user == null) {
                flag = false;

                response.setStatus(HttpStatus.SC_BAD_REQUEST);
                response.setContentType(MediaType.APPLICATION_JSON);
                response.getWriter().print(FailResult.toJson(Code.UNLOGIN, ""));
            }
        } else {
            flag = false;

            response.setStatus(HttpStatus.SC_BAD_REQUEST);
            response.setContentType(MediaType.APPLICATION_JSON);
            response.getWriter().print(FailResult.toJson(Code.SESSION_TIMEOUT, "SESSION"));
        }
    }

    return flag;
}

From source file:info.magnolia.cms.security.SecurityFilter.java

/**
 * Authenticate on basic headers./*from  w w w . ja va 2 s .co m*/
 * @param request HttpServletRequest
 * @param response HttpServletResponst
 * @return <code>true</code> if the user is authenticated
 */
private boolean authenticate(HttpServletRequest request, HttpServletResponse response) {
    try {
        if (Path.getURI(request).startsWith(this.filterConfig.getInitParameter(UNSECURED_URI))) {
            return true;
        }
        if (!Authenticator.authenticate(request)) {
            // invalidate previous session

            HttpSession httpsession = request.getSession(false);
            if (httpsession != null) {
                httpsession.invalidate();
            }
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            if (StringUtils.equalsIgnoreCase(this.filterConfig.getInitParameter(AUTH_TYPE), AUTH_TYPE_BASIC)) {
                response.setHeader("WWW-Authenticate", "BASIC realm=\"" + Server.getBasicRealm() + "\"");
            } else {
                request.getRequestDispatcher(this.filterConfig.getInitParameter(LOGIN_FORM)).include(request,
                        response);
            }
            return false;
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return false;
    }

    return true;
}

From source file:com.boundlessgeo.geoserver.AppAuthFilter.java

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) servletRequest;
    HttpServletResponse res = (HttpServletResponse) servletResponse;
    String path = req.getPathInfo();

    if (req.getServletPath().startsWith("/app") && path.startsWith("/api")) {

        if ("POST".equalsIgnoreCase(req.getMethod()) && LOGIN_RE.matcher(path).matches()) {
            // hack: we have to jump through a few hoops to piggy back on the geoserver web auth:
            // 1. we fake the request path to fool the security filter
            // 2. we ignore redirects
            boolean success = runSecurityFilters(new HttpServletRequestWrapper(req) {
                @Override/*from   w ww.jav a2 s.  c o  m*/
                public String getServletPath() {
                    return "";
                }

                @Override
                public String getPathInfo() {
                    return "/j_spring_security_check";
                }
            }, new HttpServletResponseWrapper(res) {
                @Override
                public void sendRedirect(String location) throws IOException {
                }
            }, WEB_LOGIN_CHAIN_NAME);

            if (success) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                res.setStatus(401);
            }

        } else if (LOGOUT_RE.matcher(path).matches()) {
            // invalidate the session if it exists
            HttpSession session = req.getSession(false);
            if (session != null) {
                session.invalidate();
            }
        } else {
            // two modes of authentication, basic vs form.
            String chainName = req.getHeader("Authorization") != null ? DEFAULT_CHAIN_NAME : WEB_CHAIN_NAME;
            if (runSecurityFilters(req, res, chainName)) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                res.setStatus(401);
            }
        }
    } else {
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

From source file:org.apache.archiva.redback.rest.services.DefaultLoginService.java

public Boolean logout() throws RedbackServiceException {
    HttpSession httpSession = httpServletRequest.getSession();
    if (httpSession != null) {
        httpSession.invalidate();
    }/*  ww  w.j  a v  a 2s  .  c o  m*/
    return Boolean.TRUE;
}

From source file:nl.strohalm.cyclos.controls.mobile.MobileLogoutAction.java

@Override
public ActionForward execute(final ActionMapping actionMapping, final ActionForm actionForm,
        final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    final HttpSession session = request.getSession(false);
    String queryString = null;// ww w  .  ja va 2 s.  c  o m

    if (session != null) {
        queryString = StringUtils.trimToNull((String) session.getAttribute("loginQueryString"));
        session.invalidate();
    }
    ActionForward actionForward = actionMapping.findForward("success");

    if (queryString != null) {
        actionForward = new ActionForward(actionForward);
        actionForward.setPath(actionForward.getPath() + "?" + queryString);
    }

    return actionForward;
}

From source file:ec.com.espe.arqui.web.LoginBean.java

public void logout() {
    enNuuevoCliente = false;//from ww w  .java  2  s.  com
    HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext()
            .getSession(false);
    session.invalidate();

    loggedIn = false;
}

From source file:org.appverse.web.framework.backend.frontfacade.rest.authentication.controllers.BasicAuthenticationRESTController.java

/**
 * Authenticates an user. Requires basic authentication header.
 * @param httpServletRequest//  ww w .  j a  va  2  s.  c  o m
 * @param httpServletResponse
 * @return
 * @throws Exception
 */
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("login")
public Response login(@Context HttpServletRequest httpServletRequest,
        @Context HttpServletResponse httpServletResponse) throws Exception {

    String[] userNameAndPassword;

    // Invalidate session if exists
    HttpSession httpSession = httpServletRequest.getSession(false);
    if (httpSession != null)
        httpSession.invalidate();

    authenticationServiceFacade = (AuthenticationServiceFacade) applicationContext
            .getBean(AUTHENTICATION_SERVICE_NAME);

    try {
        userNameAndPassword = obtainUserAndPasswordFromBasicAuthenticationHeader(httpServletRequest);
    } catch (BadCredentialsException e) {
        httpServletResponse.addHeader("WWW-Authenticate", "Basic");
        return Response.status(Response.Status.UNAUTHORIZED).entity(new AuthorizationDataVO()).build();
    }

    //Create and set the cookie
    httpServletRequest.getSession(true);
    String jsessionId = httpServletRequest.getSession().getId();
    Cookie sessionIdCookie = new Cookie("JSESSIONID", jsessionId);
    httpServletResponse.addCookie(sessionIdCookie);

    // Obtain XSRFToken and add it as a response header
    String xsrfToken = SecurityHelper.createXSRFToken(httpServletRequest);
    httpServletResponse.addHeader(SecurityHelper.XSRF_TOKEN_NAME, xsrfToken);

    // Authenticate principal and return authorization data
    AuthorizationDataVO authData = authenticationServiceFacade.authenticatePrincipal(userNameAndPassword[0],
            userNameAndPassword[1]);

    // AuthorizationDataVO
    return Response.status(Response.Status.OK).entity(authData).build();
}

From source file:org.dogtagpki.server.rest.AccountService.java

@Override
public Response logout() {
    HttpSession session = servletRequest.getSession(false);
    if (session == null)
        return createNoContentResponse();

    logger.info("Destroying session " + session.getId());
    session.invalidate();

    return createNoContentResponse();
}