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:servlets.MobileLogin.java

/** 
 * Initiated by login.jsp. Once this post request has been completely processed, the user will be logged in, the account will be one count closer to been temporarily been locked or will be locked out temporarily.
 * This method takes the credentials submitted and determines if they are correct. If they are correct, a session is prepared for the user and they are assigned a CSRF token.
 * @param login User's User Name//from   w  w  w. j  av a2  s. co m
 * @param pwd User's Password      
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //Setting IpAddress To Log and taking header for original IP if forwarded from proxy
    ShepherdLogManager.setRequestIp(request.getRemoteAddr(), request.getHeader("X-Forwarded-For"));
    log.debug("**** servlets.MobileLogin ***");
    HttpSession ses = request.getSession(true);
    PrintWriter out = response.getWriter();
    out.print(getServletInfo());
    response.setContentType("application/json");
    // params
    String p_login = request.getParameter("login");
    log.debug("userName: " + p_login);
    String p_pwd = request.getParameter("pwd");
    String csrfToken = new String();

    boolean authenticated = false;

    // session is not new, try to set credentials
    p_login = nvl(p_login, (String) ses.getAttribute("login"));
    p_pwd = nvl(p_pwd, (String) ses.getAttribute("password"));
    // get credentials
    String ApplicationRoot = getServletContext().getRealPath("");
    try {
        String user[] = Getter.authUser(ApplicationRoot, p_login, p_pwd);
        if (user != null && !user[0].isEmpty()) {

            //Kill Session and Create a new one with user logged in
            log.debug("Creating new session for " + user[2] + " " + user[1]);
            ses.invalidate();
            ses = request.getSession(true);
            ses.setAttribute("userStamp", user[0]);
            ses.setAttribute("userName", user[1]);
            ses.setAttribute("userRole", user[2]);
            //Used to make returned Keys user specific. Transferred to Exposed Server
            String encyptedUserName = Hash.encrypt(Hash.userNameKey, p_login);
            ses.setAttribute("ThreadSequenceId", encyptedUserName);
            log.debug("userClassId = " + user[4]);

            ses.setAttribute("userClass", user[4]);
            log.debug("Setting CSRF cookie");
            csrfToken = Hash.randomString();
            Cookie token = new Cookie("token", csrfToken);
            if (request.getRequestURL().toString().startsWith("https"))//If Requested over HTTPs
                token.setSecure(true);
            response.addCookie(token);
            authenticated = true;

            if (user[3].equalsIgnoreCase("true")) {
                log.debug("Temporary Password Detected, user will be prompted to change");
                ses.setAttribute("ChangePassword", "true");
            }
            //Removing user from kick list. If they were on it before, their suspension must have ended if they DB authentication Succeeded
            UserKicker.removeFromKicklist(user[1]);
        }
    } catch (Exception e) {
        log.error("Could not Find User: " + e.toString());
    }
    if (authenticated) {
        //returning SessionID and CSRF Token
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("JSESSIONID", ses.getId());
        jsonObj.put("token", csrfToken);
        out.write(jsonObj.toString());
        return;
    } else {
        //Lagging Response
        try {
            Thread.sleep(2000);
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
        out.write("ERROR: Could not Authenticate");
        return;
    }
}

From source file:com.funambol.transport.http.server.Sync4jServlet.java

/**
 * Invalidates the http session//w  ww.  j a v  a2s .  co m
 *
 * @param session the session to close
 */
private void closeSession(HttpSession session) {
    try {
        session.invalidate();
    } catch (Exception e) {
        log.error("Error closing the session", e);
    }
}

From source file:org.jasig.portal.security.mvc.LogoutController.java

/**
 * Process the incoming request and response.
 * @param request HttpServletRequest object
 * @param response HttpServletResponse object
 * @throws ServletException/*from  w  w  w.  j  av  a2  s. c  om*/
 * @throws IOException
 */
@RequestMapping
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String redirect = this.getRedirectionUrl(request);
    final HttpSession session = request.getSession(false);

    if (session != null) {
        // Record that an authenticated user is requesting to log out
        try {
            final IPerson person = personManager.getPerson(request);
            if (person != null && person.getSecurityContext().isAuthenticated()) {
                this.portalEventFactory.publishLogoutEvent(request, this, person);
            }
        } catch (final Exception e) {
            log.error("Exception recording logout " + "associated with request " + request, e);
        }

        final String originalUid = this.identitySwapperManager.getOriginalUsername(session);
        //Logging out from a swapped user, just redirect to the Login servlet
        if (originalUid != null) {
            redirect = request.getContextPath() + "/Login";
        } else {
            // Clear out the existing session for the user
            try {
                session.invalidate();
            } catch (final IllegalStateException ise) {
                // IllegalStateException indicates session was already invalidated.
                // This is fine.  LogoutController is looking to guarantee the logged out session is invalid;
                // it need not insist that it be the one to perform the invalidating.
                if (log.isTraceEnabled()) {
                    log.trace(
                            "LogoutController encountered IllegalStateException invalidating a presumably already-invalidated session.",
                            ise);
                }
            }
        }
    }

    // Send the user back to the guest page
    final String encodedRedirectURL = response.encodeRedirectURL(redirect);
    response.sendRedirect(encodedRedirectURL);
}

From source file:com.tremolosecurity.proxy.SessionManagerImpl.java

@Override
public void clearSession(UrlHolder holder, HttpSession sharedSession, HttpServletRequest request,
        HttpServletResponse response) {//from   w w w.  ja va2  s  .  c om
    Cookie sessionCookie;
    sessionCookie = new Cookie(holder.getApp().getCookieConfig().getSessionCookieName(), "LOGGED_OUT");
    String domain = ProxyTools.getInstance().getCookieDomain(holder.getApp().getCookieConfig(), request);
    if (domain != null) {
        sessionCookie.setDomain(domain);
    }
    sessionCookie.setPath("/");
    sessionCookie.setSecure(false);
    sessionCookie.setMaxAge(0);
    response.addCookie(sessionCookie);
    sharedSession.invalidate();

}

From source file:org.apereo.portal.security.mvc.LogoutController.java

/**
 * Process the incoming request and response.
 * @param request HttpServletRequest object
 * @param response HttpServletResponse object
 * @throws ServletException//from   www . jav  a 2s. c  om
 * @throws IOException
 */
@RequestMapping
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String redirect = this.getRedirectionUrl(request);
    final HttpSession session = request.getSession(false);

    if (session != null) {
        // Record that an authenticated user is requesting to log out
        try {
            final IPerson person = personManager.getPerson(request);
            if (person != null && person.getSecurityContext().isAuthenticated()) {
                this.portalEventFactory.publishLogoutEvent(request, this, person);
            }
        } catch (final Exception e) {
            log.error("Exception recording logout " + "associated with request " + request, e);
        }

        final String originalUid = this.identitySwapperManager.getOriginalUsername(session);
        //Logging out from a swapped user, just redirect to the Login servlet
        if (originalUid != null) {
            redirect = request.getContextPath() + "/Login";
        } else {
            // Clear out the existing session for the user
            try {
                session.invalidate();
            } catch (final IllegalStateException ise) {
                // IllegalStateException indicates session was already invalidated.
                // This is fine.  LogoutController is looking to guarantee the logged out session is invalid;
                // it need not insist that it be the one to perform the invalidating.
                if (log.isTraceEnabled()) {
                    log.trace(
                            "LogoutController encountered IllegalStateException invalidating a presumably already-invalidated session.",
                            ise);
                }
            }
        }
    }

    if (log.isTraceEnabled()) {
        log.trace("Redirecting to " + redirect + " to send the user back to the guest page.");
    }

    final String encodedRedirectURL = response.encodeRedirectURL(redirect);
    response.sendRedirect(encodedRedirectURL);
}

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

/**
  * Attempts to retrieve the User object stored in the current session.
  * //w  w w .  j  a v a2 s. c  o  m
  * @param sc
  *            the servlet context
  * @param httpRequest
  *            The HTTP request
  * @param httpResponse
  *            The HTTP response
  * @return The User object representing the current user or null if it could not be found
  */
public static User getUser(final ServletContext sc, final HttpServletRequest httpRequest,
        HttpServletResponse httpResponse) {
    // If the remote user mapper is configured, we may be able to map in an externally authenticated user
    String userId = getRemoteUser(sc, httpRequest);

    final WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
    HttpSession session = httpRequest.getSession();
    User user = null;

    // examine the appropriate session to try and find the User object
    SessionUser sessionUser = Application.getCurrentUser(session);

    // Make sure the ticket is valid, the person exists, and the cached user is of the right type (WebDAV users have
    // been known to leak in but shouldn't now)
    if (sessionUser != null) {
        if (logger.isDebugEnabled())
            logger.debug("SessionUser is: " + sessionUser.getUserName());
        AuthenticationService auth = (AuthenticationService) wc.getBean(AUTHENTICATION_SERVICE);
        try {
            auth.validate(sessionUser.getTicket());
            if (sessionUser instanceof User) {
                user = (User) sessionUser;
                setExternalAuth(session, userId != null);
            } else {
                user = setUser(sc, httpRequest, sessionUser.getUserName(), sessionUser.getTicket(),
                        userId != null);
            }
        } catch (AuthenticationException authErr) {
            if (logger.isDebugEnabled())
                logger.debug("An authentication error occured while setting the session user", authErr);
            session.removeAttribute(AUTHENTICATION_USER);
            if (!Application.inPortalServer()) {
                if (logger.isDebugEnabled())
                    logger.debug("Invalidating the session.");
                session.invalidate();
            }
        }
    }

    // If the remote user mapper is configured, we may be able to map in an externally authenticated user
    if (userId != null) {
        AuthorityService authorityService = (AuthorityService) wc.getBean(AUTHORITY_SERVICE);
        // We have a previously-cached user with the wrong identity - replace them
        if (user != null && !authorityService.isGuestAuthority(user.getUserName())
                && !user.getUserName().equals(userId)) {
            if (logger.isDebugEnabled())
                logger.debug("We have a previously-cached user with the wrong identity - replace them");
            session.removeAttribute(AUTHENTICATION_USER);
            if (!Application.inPortalServer()) {
                if (logger.isDebugEnabled())
                    logger.debug("Invalidating session.");
                session.invalidate();
            }
            user = null;
        }

        if (user == null) {
            if (logger.isDebugEnabled())
                logger.debug("There are no previously-cached users.");
            // If we have been authenticated by other means, just propagate through the user identity
            AuthenticationComponent authenticationComponent = (AuthenticationComponent) wc
                    .getBean(AUTHENTICATION_COMPONENT);
            try {
                if (logger.isDebugEnabled())
                    logger.debug(
                            "We have been authenticated by other means, authenticating the user: " + userId);
                authenticationComponent.setCurrentUser(userId);
                AuthenticationService authenticationService = (AuthenticationService) wc
                        .getBean(AUTHENTICATION_SERVICE);
                user = setUser(sc, httpRequest, userId, authenticationService.getCurrentTicket(), true);
            } catch (AuthenticationException authErr) {
                if (logger.isDebugEnabled())
                    logger.debug("An authentication error occured while setting the session user", authErr);
                // Allow for an invalid external user ID to be indicated
                session.removeAttribute(AUTHENTICATION_USER);
                if (!Application.inPortalServer()) {
                    if (logger.isDebugEnabled())
                        logger.debug("Invalidating the session.");
                    session.invalidate();
                }
            }
        }
    }
    return user;
}

From source file:com.poscoict.license.service.BoardService.java

public String checkLogin2(String text, String securedPassword, HttpSession session, HttpServletRequest request)
        throws UserException {
    logger.info("checkLogin: " + text);
    String url = "redirect:/board";
    int check = 0;

    PrivateKey privateKey = (PrivateKey) session.getAttribute("__rsaPrivateKey__");
    session.invalidate();
    session = request.getSession();//from   w w  w  .ja  v a 2 s.  c  om

    if ((text.trim() != "") && (securedPassword.trim() != "")) {
        if (privateKey == null) {
            throw new UserException("   ?  .");
        }
        try {
            check = userDao.loginCheck(text.trim(), decryptRsa(privateKey, securedPassword));
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (check == 1) {
            UserInfo user = userDao.get(text.trim());
            session.setAttribute("USER_NO", user.getUSER_NO());
            session.setAttribute("USER_NAME", user.getUSER_NAME());
            session.setAttribute("USER_PASSWORD", user.getUSER_PASSWORD());
            session.setAttribute("USER_TYPE", user.getUSER_TYPE());
            if (user.getUSER_TYPE().equals("D")) {
                session.setAttribute("SUPER_USER", true);
            } else if (user.getUSER_TYPE().equals("S")) {
                session.setAttribute("SUBCONTRACT", true);
            } else if (user.getUSER_TYPE().equals("U")) {
                session.setAttribute("PUBLIC_USER", true);
            } else {
                session.setAttribute("GUEST_USER", true);
            }

            if (!user.getUSER_TYPE().equals("G") && user.getUSER_NO().equals(user.getUSER_PASSWORD())) {
                session.setAttribute("changePassword", true);
            }
            logger.info("checkLogin: " + text + " USER_TYPE " + user.getUSER_TYPE());
        } else {
            url = "redirect:/popup/error.jsp";
            session.setAttribute("msg", "?    .");
            session.setAttribute("send", "/index.jsp");
            logger.info("checkLogin: " + text + " ?    .");
        }
    } else {
        url = "redirect:/popup/error.jsp";
        session.setAttribute("msg", "?  .");
        session.setAttribute("send", "/index.jsp");
    }
    logger.info("checkLogin: success " + text);
    return url;
}

From source file:nl.strohalm.cyclos.controls.access.ExternalLoginAction.java

private Status doLogin(final ActionForm actionForm, final HttpServletRequest request,
        final HttpServletResponse response) {
    final LoginForm form = (LoginForm) actionForm;
    final HttpSession session = request.getSession();

    // Get the parameters
    final String member = StringUtils.trimToNull(form.getMember());
    final String principal = StringUtils.trimToNull(form.getPrincipal());
    final String password = StringUtils.trimToNull(form.getPassword());

    // Check for missing parameters
    if (principal == null) {
        return Status.MISSING_USERNAME;
    } else if (password == null) {
        return Status.MISSING_PASSWORD;
    }/*from   w  w  w . ja  v a  2 s .c o  m*/

    // Perform the login
    try {
        loginHelper.login(User.class, form.getPrincipalType(), member, principal, password, Channel.WEB,
                request, response);
        return Status.SUCCESS;
    } catch (final BlockedCredentialsException e) {
        return Status.BLOCKED;
    } catch (final InactiveMemberException e) {
        return Status.INACTIVE;
    } catch (final AlreadyConnectedException e) {
        return Status.ALREADY_CONNECTED;
    } catch (final PermissionDeniedException e) {
        session.invalidate();
        return Status.PERMISSION_DENIED;
    } catch (final LoginException e) {
        return Status.INVALID;
    } catch (final Exception e) {
        actionHelper.generateLog(request, getServlet().getServletContext(), e);
        return Status.UNKNOWN_ERROR;
    }
}

From source file:it.cnr.icar.eric.client.ui.thin.RegistryBrowser.java

public String doLogout() {
    HttpSession httpSession = (HttpSession) FacesContext.getCurrentInstance().getExternalContext()
            .getSession(false);/*from ww  w .  j  a va  2 s  . co  m*/
    httpSession.invalidate();
    return "logout";
}

From source file:it.cnr.icar.eric.client.ui.thin.RegistryBrowser.java

public void doEndSession() {
    try {/*from w w  w  .j  av a2  s.co  m*/
        clearCredentials();
        if (isAuthenticated()) {
            isCertLoaded = false;
        }
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext()
                .getSession(false);
        session.invalidate();
    } catch (Exception ex) {
        log.error(WebUIResourceBundle.getInstance().getString("errorWhileRemovingSession") + ex.getMessage());
    }
    this.principalName = null;
}