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:controllers.ServerController.java

public void logout(HttpServletRequest request, HttpServletResponse response)
        throws IOException, InterruptedException, ServletException {
    HttpSession session = request.getSession(false);
    session.invalidate();
    RequestDispatcher rd = request.getRequestDispatcher("index.html");
    rd.forward(request, response);// w ww  .  j  av  a  2  s.c  om
}

From source file:architecture.user.spring.controller.SecurityController.java

@RequestMapping(value = "/logout", method = { RequestMethod.POST, RequestMethod.GET })
public View logout(@RequestParam(value = "url", defaultValue = "/", required = false) String url,
        HttpSession session, NativeWebRequest request) throws NotFoundException, IOException {
    session.invalidate();
    return new RedirectView(url, true);
}

From source file:org.finra.dm.app.AbstractAppTest.java

/**
 * Invalidated the user in session and also clears the spring security context.
 *//*from   w ww.j a  v a2 s.  c  o m*/
protected void invalidateApplicationUser(HttpServletRequest request) {
    if (request != null) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }
    }

    SecurityContextHolder.clearContext();
}

From source file:easyproject.bean.UserBean.java

public String doSignOut() {
    HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext()
            .getSession(false);//from   ww w . j a v  a 2  s  .  com
    if (session != null) {
        session.invalidate();
    }
    user = new User();
    email = "";
    image = "";
    return "PageTitle";
}

From source file:mitm.djigzo.web.services.security.InvalidateUserSpringSecurityFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest)) {
        throw new ServletException("HttpServletRequest expected.");
    }//from   w w  w .ja  v a  2s  . c o  m

    if (!(response instanceof HttpServletResponse)) {
        throw new ServletException("HttpServletResponse expected.");
    }

    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;

    String loggedInUserName = null;

    Authentication loggedInUser = SecurityContextHolder.getContext().getAuthentication();

    if (loggedInUser != null) {
        loggedInUserName = loggedInUser.getName();
    }

    if (loggedInUserName != null) {
        String email = StringUtils.trimToNull(request.getParameter(usernameRequestParameter));

        if (email != null) {
            email = EmailAddressUtils.canonicalize(email);

            if (!email.equals(loggedInUserName)) {
                /*
                 * The user has changed, so invalidate session
                 */
                HttpSession session = httpServletRequest.getSession(false);

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

                SecurityContextHolder.clearContext();

                /*
                 * We need to 'reload' the complete request to make sure the user need to login
                 */
                StringBuffer redirectURL = httpServletRequest.getRequestURL();

                if (httpServletRequest.getQueryString() != null) {
                    redirectURL.append("?").append(httpServletRequest.getQueryString());
                }

                httpServletResponse.sendRedirect(httpServletResponse.encodeRedirectURL(redirectURL.toString()));

                return;
            }
        }
    }

    chain.doFilter(request, response);
}

From source file:org.opendatakit.aggregate.servlet.MultimodeLoginPageServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    CallingContext cc = ContextFactory.getCallingContext(this, req);

    // Check to make sure we are using the canonical server name.
    // If not, redirect to that name.  This ensures that authentication
    // cookies will have the proper realm(s) established for them.
    String newUrl = cc.getServerURL() + BasicConsts.FORWARDSLASH + ADDR;
    String query = req.getQueryString();
    if (query != null && query.length() != 0) {
        newUrl += "?" + query;
    }//from  ww w .  j a  v  a  2s.  com
    URL url = new URL(newUrl);
    if (!url.getHost().equalsIgnoreCase(req.getServerName())) {
        logger.info("Incoming servername: " + req.getServerName() + " expected: " + url.getHost()
                + " -- redirecting.");
        // try to get original destination URL from Spring...
        String redirectUrl = getRedirectUrl(req, ADDR);
        try {
            URI uriChangeable = new URI(redirectUrl);
            URI newUri = new URI(url.getProtocol(), null, url.getHost(), url.getPort(), uriChangeable.getPath(),
                    uriChangeable.getQuery(), uriChangeable.getFragment());
            newUrl = newUri.toString();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        // go to the proper page (we'll most likely be redirected back to here for authentication)
        resp.sendRedirect(newUrl);
        return;
    }

    // OK. We are using the canonical server name.
    String redirectParamString = getRedirectUrl(req, AggregateHtmlServlet.ADDR);
    // we need to appropriately cleanse this string for the OpenID login
    // strip off the server pathname portion
    if (redirectParamString.startsWith(cc.getSecureServerURL())) {
        redirectParamString = redirectParamString.substring(cc.getSecureServerURL().length());
    } else if (redirectParamString.startsWith(cc.getServerURL())) {
        redirectParamString = redirectParamString.substring(cc.getServerURL().length());
    }
    while (redirectParamString.startsWith("/")) {
        redirectParamString = redirectParamString.substring(1);
    }

    // check for XSS attacks. The redirect string is emitted within single and double
    // quotes. It is a URL with :, /, ? and # characters. But it should not contain 
    // quotes, parentheses or semicolons.
    String cleanString = redirectParamString.replaceAll(BAD_PARAMETER_CHARACTERS, "");
    if (!cleanString.equals(redirectParamString)) {
        logger.warn("XSS cleanup -- redirectParamString has forbidden characters: " + redirectParamString);
        redirectParamString = cleanString;
    }

    logger.info("Invalidating login session " + req.getSession().getId());
    // Invalidate session.
    HttpSession s = req.getSession();
    if (s != null) {
        s.invalidate();
    }
    // Display page.
    resp.setContentType(HtmlConsts.RESP_TYPE_HTML);
    resp.setCharacterEncoding(HtmlConsts.UTF8_ENCODE);
    resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    resp.setHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT");
    resp.setHeader("Pragma", "no-cache");
    resp.addHeader(HtmlConsts.X_FRAME_OPTIONS, HtmlConsts.X_FRAME_SAMEORIGIN);
    PrintWriter out = resp.getWriter();
    out.print(
            "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"
                    + "<html>" + "<head>"
                    + "<meta http-equiv=\"cache-control\" content=\"no-store, no-cache, must-revalidate\"/>"
                    + "<meta http-equiv=\"expires\" content=\"Mon, 26 Jul 1997 05:00:00 GMT\"/>"
                    + "<meta http-equiv=\"pragma\" content=\"no-cache\"/>"
                    + "<link rel=\"icon\" href=\"favicon.ico\"/>" + "<title>Log onto Aggregate</title>"
                    + "<link type=\"text/css\" rel=\"stylesheet\" href=\"AggregateUI.css\">"
                    + "<link type=\"text/css\" rel=\"stylesheet\" href=\"stylesheets/button.css\">"
                    + "<link type=\"text/css\" rel=\"stylesheet\" href=\"stylesheets/table.css\">"
                    + "<link type=\"text/css\" rel=\"stylesheet\" href=\"stylesheets/navigation.css\">"
                    + "<script type=\"text/javascript\">" + "window.onbeforeunload=function() {\n"
                    + "var e=document.getElementById(\"stale\");\n" + "e.value=\"yes\";\n" + "}\n"
                    + "window.onload=function(){\n" + "var e=document.getElementById(\"stale\");\n"
                    + "if(e.value==\"yes\") {window.location.reload(true);}\n" + "}\n" + "</script>" + "</head>"
                    + "<body>" + "<input type=\"hidden\" id=\"stale\" value=\"no\">"
                    + "<table width=\"100%\" cellspacing=\"30\"><tr>"
                    + "<td align=\"LEFT\" width=\"10%\"><img src=\"odk_color.png\" id=\"odk_aggregate_logo\" /></td>"
                    + "<td align=\"LEFT\" width=\"90%\"><font size=\"7\">Log onto Aggregate</font></td></tr></table>"
                    + "<table cellspacing=\"20\">" + "<tr><td valign=\"top\">"
                    + "<form action=\"local_login.html\" method=\"get\">" + "<script type=\"text/javascript\">"
                    + "<!--\n" + "document.write('<input name=\"redirect\" type=\"hidden\" value=\""
                    + redirectParamString + "' + window.location.hash + '\"/>');" + "\n-->" + "</script>"
                    + "<input class=\"gwt-Button\" type=\"submit\" value=\"Sign in with Aggregate password\"/>"
                    + "</form></td>"
                    + "<td valign=\"top\">Click this button to log onto Aggregate using the username "
                    + "and password that have been assigned to you by the Aggregate site administrator.</td></tr>"
                    + "<tr><td valign=\"top\">" + "<script type=\"text/javascript\">" + "<!--\n"
                    + "document.write('<form action=\"" + redirectParamString
                    + "' + window.location.hash + '\" method=\"get\">');"
                    + "document.write('<input class=\"gwt-Button\" type=\"submit\" value=\"Anonymous Access\"/></form>');"
                    + "\n-->" + "</script>" + "</td>"
                    + "<td valign=\"top\">Click this button to access Aggregate without logging in.</td></tr>"
                    + "</table>" + "</body>" + "</html>");
}

From source file:org.saiku.web.service.SessionService.java

public void logout(HttpServletRequest req) {
    if (SecurityContextHolder.getContext() != null
            && SecurityContextHolder.getContext().getAuthentication() != null) {
        Object p = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (sessionHolder.containsKey(p)) {
            sessionHolder.remove(p);/*ww  w  . j a  va 2s  . c  o m*/
        }
    }
    SecurityContextHolder.getContext().setAuthentication(null);
    SecurityContextHolder.clearContext();
    HttpSession session = req.getSession(false);
    if (session != null) {
        session.invalidate();
    }
}

From source file:com.nec.harvest.security.handler.HarvestLogoutSuccessHandler.java

/**
 * Causes a logout to be completed. The method must complete successfully
 * //from   w w  w  .j av  a 2s . c  om
 * @param request
 * @param response
 * @param authentication
 * @throws IOException
 * @throws ServletException
 */
protected void onLogout(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
        throws IOException, ServletException {
    final HttpSession session = request.getSession();
    if (session != null) {
        // ??????????
        session.invalidate();

        // Invalidates this session then unbinds any objects bound to it
        logger.info(
                "??????????");
    }

    // Remove from LRU Cache
    AuthenticatedUserDetails.removeUserPrincipal();

    // The {} successfully logged out...
    String username = authentication != null ? authentication.getName() : "HARVEST SYSTEM";
    logger.info("The {} successfully logged out...", username);

    // Empty authentication
    SecurityContextHolder.getContext().setAuthentication(null);

    // Redirect to LOGIN
    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType(HttpServletContentType.PLAN_TEXT);
    response.sendRedirect(request.getContextPath() + "/login");
    response.flushBuffer();
}

From source file:fr.mycellar.interfaces.web.services.security.SecurityWebService.java

@POST
@Path("logout")
public void logout(@Context HttpServletRequest httpServletRequest) {
    HttpSession session = httpServletRequest.getSession(false);
    if (session != null) {
        session.invalidate();
    }// w ww.  ja  v  a 2s  . c  o  m

    SecurityContext context = SecurityContextHolder.getContext();
    context.setAuthentication(null);

    SecurityContextHolder.clearContext();
}

From source file:pt.iflow.servlets.AuthenticationServlet.java

static AuthenticationResult authenticate(final HttpServletRequest request, final HttpServletResponse response,
        final String username, final String password, final String nextUrl)
        throws ServletException, IOException {
    AuthenticationResult result = new AuthenticationResult();
    result.nextUrl = nextUrl;/*from   w  w  w.  jav a2  s .c om*/

    HttpSession session = request.getSession();

    Boolean bIsSystem = (Boolean) session.getAttribute(ADMIN_SESSION_NAME);
    boolean isSystem = false;

    if (bIsSystem != null)
        isSystem = bIsSystem.booleanValue();

    String login = username;
    if (login != null) {
        login = login.trim();
    }

    boolean licenseOk = LicenseServiceFactory.getLicenseService().isLicenseOK();

    AuthProfile ap = BeanFactory.getAuthProfileBean();

    UserInfoInterface ui = null;

    if (isSystem)
        ui = BeanFactory.getUserInfoFactory().newSystemUserInfo();
    else
        ui = BeanFactory.getUserInfoFactory().newUserInfo();

    Hashtable<String, String> cookies = ServletUtils.getCookies(request);
    if (cookies != null) {
        ui.setCookieLang(cookies.get(Const.LANG_COOKIE));
    }

    ui.login(login, password);

    // check license status
    if (!licenseOk && !isSystem) {
        result.nextUrl = "Admin/login.jsp";
        session.invalidate();
        return result;
    }

    boolean isAuth = result.isAuth = ui.isLogged();

    if (isAuth) {

        /////////////////////////////
        //
        // Now set some session vars
        //
        /////////////////////////////

        //Application Data
        session.setAttribute("login", login);

        session.setAttribute(Const.USER_INFO, ui);
        UserSettings settings = ui.getUserSettings();
        OrganizationData orgData = ap.getOrganizationInfo(ui.getOrganization());
        session.setAttribute(Const.ORG_INFO, orgData);

        OrganizationTheme orgTheme = BeanFactory.getOrganizationThemeBean();
        if (orgTheme != null) {
            OrganizationThemeData themeData = orgTheme.getOrganizationTheme(ui);
            session.setAttribute("themedata", themeData);
        }

        if (ui.isPasswordExpired()) {
            result.nextUrl = "changePassword";
        }

        if (!isSystem && settings.isDefault() && Const.USE_INDIVIDUAL_LOCALE && Const.ASK_LOCALE_AT_LOGIN) {
            result.nextUrl = "setupUser";
        }

        // check license status
        if (!licenseOk && isSystem) {
            result.nextUrl = "Admin/licenseValidation.jsp";
        }

        session.setAttribute("SessionHelperToken", new SimpleSessionHelper());

    } else {
        result.nextUrl = "main.jsp";
        result.errorMsg = ui.getError();
        session.setAttribute("login_error", result.errorMsg);
    }
    PersistSession ps = new PersistSession();
    ps.getSession(ui, session);
    return result;
}