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:nl.strohalm.cyclos.controls.mobile.MobileLoginAction.java

/**
 * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm,
 * javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//* w ww.j  a  va 2s .c  o  m*/
@Override
public ActionForward execute(final ActionMapping actionMapping, final ActionForm actionForm,
        final HttpServletRequest request, final HttpServletResponse response) throws Exception {

    final HttpSession session = request.getSession();

    // Test a previously logged user
    final User user = LoginHelper.getLoggedUser(request);
    if (user != null) {
        if (user instanceof MemberUser) {
            final String channel = MobileHelper.mobileChannel(request);
            if (!accessService.isChannelEnabledForMember(channel, ((MemberUser) user).getMember())) {
                session.invalidate();
                return MobileHelper.sendException(actionMapping, request, new InvalidUserForMobileException());
            } else {
                return MobileHelper.getHomeForward(actionMapping, request);
            }
        } else {
            session.invalidate();
            return MobileHelper.sendException(actionMapping, request, new InvalidUserForMobileException());
        }
    }

    // Check for a query string
    final String queryString = StringUtils.trimToNull(request.getQueryString());

    if (queryString != null) {
        // Try to find a group filter
        try {
            final GroupFilter groupFilter = groupFilterService.findByLoginPageName(queryString);
            request.setAttribute("styleGroupFilter", groupFilter);
        } catch (final EntityNotFoundException e) {
            // Try to find a group
            try {
                final Group group = groupService.findByLoginPageName(queryString);
                request.setAttribute("styleGroup", group);
            } catch (final EntityNotFoundException e1) {
                // Ignore
            }
        }
    }
    if (RequestHelper.isGet(request)) { // only in this case we should store the queryString
        session.setAttribute("loginQueryString", queryString);
    }

    ActionForward forward = null;
    try {
        // Check if is a page preparation or execution
        if (RequestHelper.isGet(request)) {
            forward = prepareForm(actionMapping, actionForm, request, response);
        } else if (RequestHelper.isPost(request)) {
            forward = doLogin(actionMapping, actionForm, request, response);
        }
    } catch (final MobileException e) {
        return MobileHelper.sendException(actionMapping, request, e);
    }
    return MobileBaseAction.processForward(forward, request);
}

From source file:org.wso2.carbon.identity.sso.agent.saml.SAML2SSOManager.java

/**
 * This method handles the logout requests from the IdP
 * Any request for the defined logout URL is handled here
 *
 * @param request//from w w w  .j av a2  s  .  c o m
 * @throws javax.servlet.ServletException
 * @throws IOException
 */
public void doSLO(HttpServletRequest request) throws SSOAgentException {

    XMLObject saml2Object = null;
    if (request.getParameter(SSOAgentConstants.SAML2SSO.HTTP_POST_PARAM_SAML2_AUTH_REQ) != null) {
        saml2Object = SSOAgentUtils.unmarshall(new String(
                Base64.decode(request.getParameter(SSOAgentConstants.SAML2SSO.HTTP_POST_PARAM_SAML2_AUTH_REQ)),
                Charset.forName("UTF-8")));
    }
    if (saml2Object == null) {
        saml2Object = SSOAgentUtils.unmarshall(new String(
                Base64.decode(request.getParameter(SSOAgentConstants.SAML2SSO.HTTP_POST_PARAM_SAML2_RESP)),
                Charset.forName("UTF-8")));
    }
    if (saml2Object instanceof LogoutRequest) {
        LogoutRequest logoutRequest = (LogoutRequest) saml2Object;
        String sessionIndex = logoutRequest.getSessionIndexes().get(0).getSessionIndex();
        Set<HttpSession> sessions = SSOAgentSessionManager.invalidateAllSessions(sessionIndex);
        for (HttpSession session : sessions) {
            session.invalidate();
        }
    } else if (saml2Object instanceof LogoutResponse) {
        if (request.getSession(false) != null) {
            /**
             * Not invalidating session explicitly since there may be other listeners
             * still waiting to get triggered and at the end of the chain session needs to be
             * invalidated by the system
             */
            Set<HttpSession> sessions = SSOAgentSessionManager.invalidateAllSessions(request.getSession(false));
            for (HttpSession session : sessions) {
                try {
                    session.invalidate();
                } catch (IllegalStateException ignore) {

                    if (log.isDebugEnabled()) {
                        log.debug("Ignoring exception : ", ignore);
                    }
                    //ignore
                    //session is already invalidated
                }
            }
        }
    } else {
        throw new SSOAgentException("Invalid SAML2 Single Logout Request/Response");
    }
}

From source file:org.emr.intercepter.RequestInterceptor.java

public boolean validateSession(HttpServletRequest request, HttpServletResponse response, FactoryBean loginBean)
        throws IOException, JSONException {
    HttpSession session = request.getSession();
    boolean status = true;
    if (session.isNew()) {
        System.out.println("new session found :");
        String username = (String) request.getParameter("username");
        String password = (String) request.getParameter("password");
        ArrayList<FactoryBean> factoryBean = model
                .select("from LoginBean where username = '" + username + "' and password = '" + password + "'");
        if (factoryBean.size() == 0) {
            System.out.println("invalidate session on first request if login failed:");
            session.invalidate();
            return false;
        }//www .j  a v  a2  s.c  om
        /*
         * get user profile : 
         */
        loginBean = (LoginBean) factoryBean.get(0);
        System.out.println("username : " + username);
        session.setAttribute("loginBean", ((LoginBean) loginBean));
        session.setMaxInactiveInterval(60);
    }
    return status;
}

From source file:org.wso2.carbon.identity.authenticator.saml2.sso.ui.SSOAssertionConsumerService.java

private void handleExternalLogout(HttpServletRequest req, HttpServletResponse resp, String externalLogoutPage)
        throws IOException {

    HttpSession currentSession = req.getSession(false);
    if (currentSession != null) {
        // check if current session has expired
        currentSession.removeAttribute(CarbonSecuredHttpContext.LOGGED_USER);
        currentSession.getServletContext().removeAttribute(CarbonSecuredHttpContext.LOGGED_USER);
        try {/*w ww  . j a  v a  2 s  .c  om*/
            currentSession.invalidate();
            if (log.isDebugEnabled()) {
                log.debug("Frontend session invalidated");
            }
        } catch (Exception ignored) {
            // Ignore exception when invalidating and invalidated session
        }
    }
    clearCookies(req, resp);

    if (log.isDebugEnabled()) {
        log.debug("Sending to " + externalLogoutPage);
    }
    resp.sendRedirect(externalLogoutPage);

}

From source file:pt.ist.vaadinframework.EmbeddedApplication.java

@Override
public void close() {
    HttpSession session = ((WebApplicationContext) getContext()).getHttpSession();
    final UserView userView = (UserView) session.getAttribute(SetUserViewFilter.USER_SESSION_ATTRIBUTE);

    if (userView != null) {
        userView.getUser().setLastLogoutDateTime(new DateTime());
    }// w ww  . j  a  v  a  2  s  .com

    pt.ist.fenixWebFramework.security.UserView.setUser(null);
    session.removeAttribute(SetUserViewFilter.USER_SESSION_ATTRIBUTE);
    session.invalidate();
    super.close();
}

From source file:org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy.java

/**
 * Called when a user is newly authenticated.
 * <p>// ww  w.j  av  a 2  s  .co m
 * If a session already exists, and matches the session Id from the client, a new session will be created, and the
 * session attributes copied to it (if {@code migrateSessionAttributes} is set).
 * If the client's requested session Id is invalid, nothing will be done, since there is no need to change the
 * session Id if it doesn't match the current session.
 * <p>
 * If there is no session, no action is taken unless the {@code alwaysCreateSession} property is set, in which
 * case a session will be created if one doesn't already exist.
 */
public void onAuthentication(Authentication authentication, HttpServletRequest request,
        HttpServletResponse response) {
    boolean hadSessionAlready = request.getSession(false) != null;

    if (!hadSessionAlready && !alwaysCreateSession) {
        // Session fixation isn't a problem if there's no session

        return;
    }

    // Create new session if necessary
    HttpSession session = request.getSession();

    if (hadSessionAlready && request.isRequestedSessionIdValid()) {
        // We need to migrate to a new session
        String originalSessionId = session.getId();

        if (logger.isDebugEnabled()) {
            logger.debug("Invalidating session with Id '" + originalSessionId + "' "
                    + (migrateSessionAttributes ? "and" : "without") + " migrating attributes.");
        }

        Map<String, Object> attributesToMigrate = extractAttributes(session);

        session.invalidate();
        session = request.getSession(true); // we now have a new session

        if (logger.isDebugEnabled()) {
            logger.debug("Started new session: " + session.getId());
        }

        if (originalSessionId.equals(session.getId())) {
            logger.warn(
                    "Your servlet container did not change the session ID when a new session was created. You will"
                            + " not be adequately protected against session-fixation attacks");
        }

        transferAttributes(attributesToMigrate, session);

        onSessionChange(originalSessionId, session, authentication);
    }
}

From source file:nl.strohalm.cyclos.controls.BaseAction.java

/**
 * The Struts standard execute method is reserved, being the executeAction the one that subclasses must implement
 *//*w w  w . ja v a 2 s.c  o m*/
@Override
public final ActionForward execute(final ActionMapping actionMapping, final ActionForm actionForm,
        final HttpServletRequest request, final HttpServletResponse response) throws Exception {

    // Check for uploads that exceeded the max length
    final Boolean maxLengthExceeded = (Boolean) request
            .getAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED);
    if (maxLengthExceeded != null && maxLengthExceeded) {
        final LocalSettings settings = settingsService.getLocalSettings();
        return ActionHelper.sendError(actionMapping, request, response, "error.maxUploadSizeExceeded",
                FileUtils.byteCountToDisplaySize(settings.getMaxUploadBytes()));
    }
    HttpSession session = request.getSession(false);

    // Validate the logged user
    User user = null;
    try {
        user = validate(request, response, actionMapping);
        if (user == null) {
            return null;
        }
    } catch (final LoggedOutException e) {
        // Invalidate the current session
        if (session != null) {
            session.invalidate();
        }
        // Create a new session
        session = request.getSession();
        ActionForward forward = resolveLoginForward(actionMapping, request);
        // If the action is stored on navigation path, we should return to it after re-login
        if (storePath(actionMapping, request)) {
            // Store the path on session, so that after logging in, the user will stay on this page
            String path = actionMapping.getPath();
            final String queryString = request.getQueryString();
            if (StringUtils.isNotEmpty(queryString)) {
                path += "?" + queryString;
            }
            session.setAttribute("returnTo", path);
            session.setAttribute("loggedOut", true);

            // Redirect to the login page
            final Map<String, Object> params = new HashMap<String, Object>();
            if (path.contains("/operator/")) {
                params.put("operator", true);
            }
            forward = ActionHelper.redirectWithParams(request, forward, params);
        }
        return forward;
    } catch (final AccessDeniedException e) {
        if (session != null) {
            session.invalidate();
        }
        return ActionHelper.sendError(actionMapping, request, response, "error.accessDenied");
    } catch (final Exception e) {
        CurrentTransactionData.setError(e);
        actionHelper.generateLog(request, getServlet().getServletContext(), e);
        LOG.error("Application error on " + getClass().getName(), e);
        return ActionHelper.sendError(actionMapping, request, response, null);
    }

    // Check if the member shall accept a registration agreement or change the expired password before proceeding
    if (session != null) {
        String forwardName = null;
        if (Boolean.TRUE.equals(session.getAttribute("shallAcceptRegistrationAgreement"))) {
            // AcceptRegistrationAgreementAction is a BasePublicFormAction, not BaseAction, so, we don't need to check if this is not that action
            forwardName = RequestHelper.isPosWeb(request) ? "poswebAcceptRegistrationAgreement"
                    : "acceptRegistrationAgreement";
        } else if (Boolean.TRUE.equals(session.getAttribute("expiredPassword"))
                && !(this instanceof ChangeExpiredPasswordAction)) {
            // Only redirect to change expired password if this is not that action

            if (RequestHelper.isPosWeb(request)) {
                forwardName = "poswebChangeExpiredPassword";
            } else {
                return actionHelper.getForwardFor(LoggedUser.element().getNature(), "changeExpiredPassword",
                        true);
            }
        }
        if (forwardName != null) {
            return actionMapping.findForward(forwardName);
        }
    }

    // Perform special actions when the request is coming from menu
    if (RequestHelper.isFromMenu(request)) {
        request.setAttribute("fromMenu", true);
    }

    // Create an action context
    final ActionContext context = new ActionContext(actionMapping, actionForm, request, response, user,
            messageHelper);
    request.setAttribute("formAction", actionMapping.getPath());

    try {
        // checks access to the action
        actionAccessMonitor.requestAccess(context);

        // Store the navigation data
        final Navigation navigation = context.getNavigation();
        if (storePath(actionMapping, request)) {
            navigation.setLastAction(actionMapping);
            navigation.store(context);
        }

        // Process the action
        final ActionForward forward = executeAction(context);
        return forward;
    } catch (final PermissionDeniedException e) {
        CurrentTransactionData.setError(e);
        final boolean userBlocked = accessService.notifyPermissionDeniedException();
        if (userBlocked) {
            request.getSession(false).invalidate();
            return ActionHelper.sendError(actionMapping, request, response, "login.error.blocked");
        } else {
            return ActionHelper.sendError(actionMapping, request, response, "error.permissionDenied");
        }
    } catch (final QueryParseException e) {
        CurrentTransactionData.setError(e);
        return ActionHelper.sendError(actionMapping, request, response, "error.queryParse");
    } catch (final ImageHelper.UnknownImageTypeException e) {
        CurrentTransactionData.setError(e);
        final String recognizedTypes = StringUtils.join(ImageType.values(), ", ");
        return ActionHelper.sendError(actionMapping, request, response, "error.unknownImageType",
                recognizedTypes);
    } catch (final ImageException e) {
        CurrentTransactionData.setError(e);
        return ActionHelper.sendError(actionMapping, request, response, e.getKey());
    } catch (final ValidationException e) {
        CurrentTransactionData.setError(e);
        return ActionHelper.handleValidationException(actionMapping, request, response, e);
    } catch (final EntityNotFoundException e) {
        // An entity not found is handled as a validation exception
        return ActionHelper.handleValidationException(actionMapping, request, response,
                new ValidationException());
    } catch (final ExternalException e) {
        CurrentTransactionData.setError(e);
        return ActionHelper.sendErrorWithMessage(actionMapping, request, response, e.getMessage());
    } catch (final Exception e) {
        CurrentTransactionData.setError(e);
        actionHelper.generateLog(request, getServlet().getServletContext(), e);
        LOG.error("Application error on " + getClass().getName(), e);
        return ActionHelper.sendError(actionMapping, request, response, null);
    }
}

From source file:org.wso2.carbon.ui.AbstractCarbonUIAuthenticator.java

/**
 * Regenerates session id after each login attempt.
 * @param request//from  w w w .ja va 2  s. c o  m
 */
private void regenrateSession(HttpServletRequest request) {

    HttpSession oldSession = request.getSession();

    Enumeration attrNames = oldSession.getAttributeNames();
    Properties props = new Properties();

    while (attrNames != null && attrNames.hasMoreElements()) {
        String key = (String) attrNames.nextElement();
        props.put(key, oldSession.getAttribute(key));
    }

    oldSession.invalidate();
    HttpSession newSession = request.getSession(true);
    attrNames = props.keys();

    while (attrNames != null && attrNames.hasMoreElements()) {
        String key = (String) attrNames.nextElement();
        newSession.setAttribute(key, props.get(key));
    }
}

From source file:org.forgerock.openidm.filter.AuthFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (router == null) {
        throw new ServletException("Internal services not ready to process requests.");
    }// w w  w . j a va  2s . c  om

    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    AuthData authData = new AuthData();

    try {
        HttpSession session = req.getSession(false);
        String logout = req.getHeader("X-OpenIDM-Logout");
        String headerLogin = req.getHeader(HEADER_USERNAME);
        String basicAuth = req.getHeader("Authorization");
        if (logout != null) {
            if (session != null) {
                session.invalidate();
            }
            res.setStatus(HttpServletResponse.SC_NO_CONTENT);
            return;
            // if we see the certficate port this request is for client auth only
        } else if (allowClientCertOnly(req)) {
            authData = hasClientCert(req);
            logAuth(req, authData.username, authData.userId, authData.roles, Action.authenticate,
                    Status.SUCCESS);
        } else if (session == null && headerLogin != null) {
            authData = authenticateUser(req);
            logAuth(req, authData.username, authData.userId, authData.roles, Action.authenticate,
                    Status.SUCCESS);
            createSession(req, session, authData);
        } else if (session == null && basicAuth != null) {
            authData = doBasicAuth(basicAuth);
            logAuth(req, authData.username, authData.userId, authData.roles, Action.authenticate,
                    Status.SUCCESS);
            createSession(req, session, authData);
        } else if (session != null) {
            authData.username = (String) session.getAttribute(USERNAME_ATTRIBUTE);
            authData.userId = (String) session.getAttribute(USERID_ATTRIBUTE);
            authData.roles = (List<String>) session.getAttribute(ROLES_ATTRIBUTE);
            authData.resource = (String) session.getAttribute(RESOURCE_ATTRIBUTE);
        } else {
            authFailed(req, res, authData.username);
            return;
        }
    } catch (AuthException s) {
        authFailed(req, res, s.getMessage());
        return;
    }
    logger.debug("Found valid session for {} id {} with roles {}",
            new Object[] { authData.username, authData.userId, authData.roles });
    req.setAttribute(USERID_ATTRIBUTE, authData.userId);
    req.setAttribute(ROLES_ATTRIBUTE, authData.roles);
    req.setAttribute(RESOURCE_ATTRIBUTE, authData.resource);
    req.setAttribute(OPENIDM_AUTHINVOKED, "openidmfilter");

    chain.doFilter(new UserWrapper(req, authData.username, authData.userId, authData.roles), res);
}

From source file:nl.strohalm.cyclos.utils.LoginHelper.java

@SuppressWarnings("rawtypes")
private HttpSession createNewSessionForlogin(final HttpServletRequest request) {
    HttpSession session = request.getSession();

    // retrieve the current attributes
    final Map<String, Object> attrMap = new HashMap<String, Object>();
    for (final Enumeration e = session.getAttributeNames(); e.hasMoreElements();) {
        final String attrName = (String) e.nextElement();
        attrMap.put(attrName, session.getAttribute(attrName));
    }/* w  w  w .  j a v  a2  s .co m*/

    // invalidates and creates a new session
    session.invalidate();
    session = request.getSession();

    // copy the previous attributes to the new session
    for (final Map.Entry<String, Object> entry : attrMap.entrySet()) {
        session.setAttribute(entry.getKey(), entry.getValue());
    }

    return session;
}