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.alfresco.repo.webdav.auth.BaseAuthenticationFilter.java

/**
 * Handles the login form directly, allowing management of the session user.
 * //from  w  w w . j  a  va 2 s  .co m
 * @param req
 *            the request
 * @param res
 *            the response
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws ServletException
 *             on error
 */
protected boolean handleLoginForm(HttpServletRequest req, HttpServletResponse res)
        throws IOException, ServletException {
    if (getLogger().isDebugEnabled())
        getLogger().debug("Handling the login form.");
    // Invalidate current session
    HttpSession session = req.getSession(false);
    if (session != null) {
        session.invalidate();
    }
    StringBuilder out = new StringBuilder(1024);
    Reader in = req.getReader();
    char[] buff = new char[1024];
    int charsRead;
    while ((charsRead = in.read(buff)) != -1) {
        out.append(buff, 0, charsRead);
    }
    in.close();

    try {
        JSONObject json = new JSONObject(out.toString());
        String username = json.getString("username");
        String password = json.getString("password");

        if (username == null || username.length() == 0) {
            if (getLogger().isDebugEnabled())
                getLogger().debug("Username not specified in the login form.");
            res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Username not specified");
            return false;
        }

        if (password == null) {
            if (getLogger().isDebugEnabled())
                getLogger().debug("Password not specified in the login form.");
            res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Password not specified");
            return false;
        }

        authenticationService.authenticate(username, password.toCharArray());
        session = req.getSession();
        createUserEnvironment(session, username, authenticationService.getCurrentTicket(), false);
        res.setStatus(HttpServletResponse.SC_NO_CONTENT);
        return true;
    } catch (AuthenticationException e) {
        if (getLogger().isDebugEnabled())
            getLogger().debug("Login failed", e);
        res.sendError(HttpServletResponse.SC_FORBIDDEN, "Login failed");
    } catch (JSONException jErr) {
        if (getLogger().isDebugEnabled())
            getLogger().debug("Unable to parse JSON POST body", jErr);
        res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "Unable to parse JSON POST body: " + jErr.getMessage());
    }
    return false;
}

From source file:org.obm.sync.server.handler.LoginHandlerTest.java

private HttpServletRequest createHttpServletRequestMock(String endpoint, final Map<String, String> parameters) {
    HttpSession session = control.createMock(HttpSession.class);
    HttpServletRequest request = control.createMock(HttpServletRequest.class);

    expect(session.getId()).andReturn("sessionId").anyTimes();
    session.invalidate();
    expectLastCall().anyTimes();/*  w w  w .j av  a  2  s .c  o  m*/

    expect(request.getRemoteAddr()).andReturn("127.0.0.1").anyTimes();
    expect(request.getHeader(isA(String.class))).andReturn(null).anyTimes();
    expect(request.getPathInfo()).andReturn("/login/" + endpoint).anyTimes();
    expect(request.getSession()).andReturn(session).anyTimes();
    expect(request.getSession(anyBoolean())).andReturn(session).anyTimes();
    expect(request.getParameterMap()).andReturn(parameters).anyTimes();
    expect(request.getParameter(isA(String.class))).andAnswer(new IAnswer<String>() {
        @Override
        public String answer() throws Throwable {
            return parameters.get(getCurrentArguments()[0]);
        }
    }).anyTimes();

    return request;
}

From source file:org.sonatype.nexus.security.filter.authc.NexusHttpAuthenticationFilter.java

@Override
public void postHandle(ServletRequest request, ServletResponse response) throws Exception {
    if (request.getAttribute(ANONYMOUS_LOGIN) != null) {
        try {//from  ww w .  jav a  2 s . c  o m
            getSubject(request, response).logout();
        } catch (UnknownSessionException e) {
            // we need to prevent log spam, just log this as trace
            this.logger.trace("Failed to find session for anonymous user.", e);
        }
        if (HttpServletRequest.class.isAssignableFrom(request.getClass())) {
            HttpSession session = ((HttpServletRequest) request).getSession(false);

            if (session != null) {
                session.invalidate();
            }
        }
    }

    if (request.getAttribute(NexusJSecurityFilter.REQUEST_IS_AUTHZ_REJECTED) != null) {
        if (request.getAttribute(ANONYMOUS_LOGIN) != null) {
            sendChallenge(request, response);
        } else {

            Subject subject = getSubject(request, response);

            String username = getNexusConfiguration().getAnonymousUsername();

            if (subject != null && subject.isAuthenticated()) {
                username = subject.getPrincipal().toString();
            }

            getLogger().info(
                    "Request processing is rejected because user \"" + username + "\" lacks permissions.");

            sendForbidden(request, response);
        }
    }
}

From source file:com.impetus.kwitter.mb.LoginBean.java

public String deleteAccount() {
    HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
    setTwitter(KwitterUtils.getTwitterService());
    String userId = (String) session.getAttribute(Constants.USER_ID);

    User user = getTwitter().findUserById(userId);

    getTwitter().removeUser(user);//from  w  w  w .j  av a 2s  . c  o  m

    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Account successfully deleted"));
    session.invalidate();
    return Constants.OUTCOME_SIGNUP_SUCCESSFUL;
}

From source file:it.govpay.web.filters.SessionTimeoutFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {

    if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        //   HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        String requestPath = httpServletRequest.getRequestURI();
        this.log.debug("Richiesta risorsa: " + requestPath);

        String principal = null;// w w  w .ja  v a 2 s . c om
        if (httpServletRequest.getUserPrincipal() != null) {
            principal = httpServletRequest.getUserPrincipal().getName();
        }

        this.log.debug("Utente: " + principal);

        // is session expire control required for this request?
        if (this.isSessionControlRequiredForThisResource(httpServletRequest)) {
            HttpSession sessione = httpServletRequest.getSession(false);

            this.log.debug("Session: " + (sessione != null ? sessione.getId() : "Null"));

            // is session invalid?
            if (this.isSessionInvalid(httpServletRequest)) {
                //String redirPageUrl = httpServletRequest.getContextPath() + "/";

                if (sessione != null)
                    sessione.invalidate();

                this.log.debug("La sessione non e' valida, effettuo redirect...");

                //se la pagina richiesta e' quella di login allora redirigo direttamente a quella, altrimenti a quella di timeout
                //redirPageUrl += StringUtils.contains(httpServletRequest.getRequestURI(), getLoginPage()) ? getLoginPage() : getTimeoutPage();
                //   redirPageUrl += getRedirPage(httpServletRequest);
                //               log.info("session is invalid! redirecting to page : " + redirPageUrl);
                //httpServletResponse.sendRedirect(redirPageUrl);
                //return;
            }
        }
    }
    filterChain.doFilter(request, response);

}

From source file:org.nuxeo.ecm.platform.ui.web.auth.service.PluggableAuthenticationService.java

public void invalidateSession(ServletRequest request) {
    boolean done = false;
    if (!sessionManagers.isEmpty()) {
        Iterator<NuxeoAuthenticationSessionManager> it = sessionManagers.values().iterator();
        while (it.hasNext() && !(done = it.next().invalidateSession(request))) {
        }//from w w  w  .  j  a  v a 2  s  .  co m
    }
    if (!done) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpSession session = httpRequest.getSession(false);
        if (session != null) {
            session.invalidate();
        }
    }
}

From source file:com.microsoft.azure.oidc.filter.helper.impl.SimpleAuthenticationHelper.java

private HttpServletRequest clearSessionCoookie(final HttpServletRequest httpRequest,
        final HttpServletResponse httpResponse, final Token token, final State state) {
    if (httpRequest == null || httpResponse == null || token == null || state == null) {
        throw new PreconditionException("Required parameter is null");
    }/*from   ww w .  j  a  v a2 s.  co  m*/
    final Cookie redisSessionCookie = getCookie(httpRequest, "SESSION");
    final Cookie javaSessionCookie = getCookie(httpRequest, "JSESSIONID");
    if (redisSessionCookie != null || javaSessionCookie != null) {
        if (token.getUserID().toString().equals(state.getUserID())) {
            if (redisSessionCookie != null && redisSessionCookie.getValue().equals(state.getSessionName())) {
                return httpRequest;
            }
            if (javaSessionCookie != null && javaSessionCookie.getValue().equals(state.getSessionName())) {
                return httpRequest;
            }
        }
        if (redisSessionCookie != null) {
            redisSessionCookie.setMaxAge(0);
            httpResponse.addCookie(redisSessionCookie);
            HttpSession session = httpRequest.getSession(false);
            if (session != null) {
                session.invalidate();
            }
        }
        if (javaSessionCookie != null) {
            javaSessionCookie.setMaxAge(0);
            httpResponse.addCookie(javaSessionCookie);
            HttpSession session = httpRequest.getSession(false);
            if (session != null) {
                session.invalidate();
            }
        }
        return new HttpServletRequestWrapper(httpRequest) {
            @Override
            public Cookie[] getCookies() {
                final List<Cookie> cookieList = new ArrayList<Cookie>();
                for (Cookie cookie : httpRequest.getCookies()) {
                    if (!cookie.getName().equals("SESSION") && !cookie.getName().equals("JSESSIONID")) {
                        cookieList.add(cookie);
                    }
                }
                final Cookie[] cookieArray = new Cookie[cookieList.size()];
                cookieList.toArray(cookieArray);
                return cookieArray;
            }
        };
    }
    return httpRequest;
}

From source file:org.openmrs.module.rwandaprimarycare.LoginController.java

@RequestMapping("logout.form")
public String logoutUser(ModelMap model, HttpSession session, HttpServletRequest request,
        HttpServletResponse response) {/*from  w w  w.  j  a  va2  s. c o  m*/

    try {

        Context.logout();

        session.removeAttribute(WebConstants.OPENMRS_USER_CONTEXT_HTTPSESSION_ATTR);
        session.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "auth.logged.out");
        session.setAttribute(WebConstants.OPENMRS_LOGIN_REDIRECT_HTTPSESSION_ATTR, request.getContextPath());
        session.invalidate();

        return "redirect:login.form";

    } catch (Exception e) {
        //TODO
        log.error("Uexpected auth error", e);
    }

    return "redirect:login.form";
}

From source file:com.logiclander.jaasmine.authentication.http.SimpleLogoutServlet.java

/**
 * Logs out the Subject associated with the user.
 *
 * After the logout is done, the request is dispatched to a Servlet or JSP
 * specified by the {@code postLogoutProcessorName} init-param.  If the
 * param was not specified, a {@code text/plain} message will be written
 * to the response.//from  ww  w  .j ava  2s .c  o  m
 *
 * This method is not idempotent.  If a request is made successfully once,
 * the user will be logged out.  Subsequent requests without a login will
 * cause an HTTP 403 - Forbidden to be returned.
 *
 * @param req the HttpServletRequest
 * @param resp the HttpServletResponse
 * @throws ServletException if a ServletException is thrown after the
 * request is dispatched to the post logout processor.
 * @throws IOException if an I/O error occurs.
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    HttpSession sess = req.getSession();
    Subject subj = (Subject) sess.getAttribute(AuthenticationService.SUBJECT_KEY);

    if (subj == null) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // Log out the Subject
    AuthenticationService as = new SimpleAuthenticationService(appName);
    as.logout(subj);

    // Invalidate the session
    sess.invalidate();

    resp.setStatus(HttpServletResponse.SC_OK);
    RequestDispatcher rd = getServletContext().getNamedDispatcher(postLogoutProcessorName);

    if (rd != null) {
        resp.setContentType("text/html");
        rd.include(req, resp);
    } else {
        sendPlainTextResponse(resp);
    }

}

From source file:org.openmrs.module.bom.web.controller.LoginPageOverrideController.java

@RequestMapping("/module/bom/logout.htm")
public String logoutUser(ModelMap model, HttpSession session, HttpServletRequest request,
        HttpServletResponse response) {/*from w  w w  .  j  a  v  a  2s .  co  m*/

    try {

        Context.logout();

        session.removeAttribute(WebConstants.OPENMRS_USER_CONTEXT_HTTPSESSION_ATTR);
        session.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "auth.logged.out");
        session.setAttribute(WebConstants.OPENMRS_LOGIN_REDIRECT_HTTPSESSION_ATTR, request.getContextPath());
        session.invalidate();

        return "/module/bom/bomLogin";

    } catch (Exception e) {
        //TODO
        log.error("Uexpected auth error", e);
    }

    return "/module/bom/bomLogin";
}