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.ProfileUpload.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w  ww  .j  a  v a  2  s . c  o  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String urlb = "img-profile/";
    String nada = "";
    HttpSession session = request.getSession(true);
    String nom_se = (String) request.getSession().getAttribute("Usuario");

    if (ServletFileUpload.isMultipartContent(request)) {
        PrintWriter out = response.getWriter();
        String url = "";
        try {
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String name = new File(item.getName()).getName();
                    item.write(new File(UPLOAD_DIRECTORY + "/" + name));
                    String urlc = nada += name;
                    url = urlb + urlc;
                }
            }
            out.print(url);
            //subido
            out.println("subido en eichdi");

            User c = new User();

            //nombre

            Statement s;
            s = c.conectar().createStatement();
            ResultSet rs;
            rs = s.executeQuery("select id_usuario from Usuarios where username = '" + nom_se + "';");

            rs.next();
            String id = rs.getString("id_usuario");

            String query = "update Usuarios set url_foto = '" + url + "' where id_usuario = '" + id + "';";
            s.executeUpdate(query);
            session.setAttribute("Foto", url);
        } catch (Exception ex) {
            response.sendRedirect("index.html");
            session.invalidate();
        }

    } else {
    }
    //request.getRequestDispatcher("/result.jsp").forward(request, response);response.setContentType("text/html;charset=UTF-8");
}

From source file:org.CloudOps.laas.ws.login.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from ww  w  . j  a  va2s.  c  o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession();
    if (session == null || session.getAttribute("apikey") == null) {
        // no session or not authenticate
        // Check for HTTP header: Authorization
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null) {
            StringTokenizer st = new StringTokenizer(authHeader);
            if (st.hasMoreTokens()) {
                String basic = st.nextToken();

                if (basic.equalsIgnoreCase("Basic")) {
                    String credentials = new String(Base64.decodeBase64(st.nextToken()), "UTF-8");
                    log.debug("Credentials: " + credentials);
                    int p = credentials.indexOf(":");
                    if (p != -1) {
                        String login = credentials.substring(0, p).trim();
                        String password = credentials.substring(p + 1).trim();

                        reloadApikeys();

                        if (apikeys.containsKey(login) && apikeys.get(login).equals(password)) {
                            log.debug("APIKEY {0} authenticated" + login);
                            if (session != null)
                                session.invalidate();
                            session = request.getSession(true);
                            session.setAttribute("apikey", login);
                        } else {
                            log.info("Invalid APIKEY(" + login + " : " + password + ")");
                            sendHttpAuth(request, response);
                            return;
                        }

                    } else {
                        log.error("Invalid authentication token " + authHeader);
                        sendHttpAuth(request, response);
                        return;
                    }
                } else {
                    log.warn("Unsupported HTTP authentication method '" + basic
                            + "', Authorization HTTP header: '" + authHeader + "'");
                    sendHttpAuth(request, response);
                    return;
                }
            } else {
                log.warn("Invalid HTTP authentication request '" + authHeader + "'");
                sendHttpAuth(request, response);
                return;
            }
        } else {
            // request for HTTP authentication
            sendHttpAuth(request, response);
            return;
        }
    }

    if (request.getParameter("logout") != null) {
        session.invalidate();
        // request for HTTP authentication
        sendHttpAuth(request, response);
        return;
    }

    String referer = request.getHeader("X-Referer");
    if (referer == null)
        referer = request.getParameter("referer");
    if (referer == null)
        referer = request.getHeader("Referer");
    if (referer != null) {
        response.sendRedirect(referer);
        return;
    }
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>CloudOps-LaaS - API login</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>You are logged with APIkey '" + session.getAttribute("apikey") + "'</h1>");
        out.println("</body>");
        out.println("</html>");
    }
}

From source file:org.craftercms.studio.impl.v1.web.security.access.StudioAuthenticationTokenProcessingFilter.java

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

    HttpServletRequest httpRequest = this.getAsHttpRequest(servletRequest);
    HttpSession httpSession = httpRequest.getSession();
    semaphore.lock();//w  ww .  j  a  v  a 2  s .com
    try {
        String userName = securityService.getCurrentUser();
        String authToken = securityService.getCurrentToken();

        if (userName != null) {
            UserDetails userDetails = this.userDetailsManager.loadUserByUsername(userName);

            if (SessionTokenUtils.validateToken(authToken, userDetails.getUsername())) {

                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authentication);

                if (httpRequest.getRequestURI().startsWith(httpRequest.getContextPath() + "/api/1")
                        && !getIgnoreRenewTokenUrls()
                                .contains(HttpUtils.getRequestUriWithoutContextPath(httpRequest))) {
                    int timeout = Integer.parseInt(studioConfiguration.getProperty(SECURITY_SESSION_TIMEOUT));
                    String newToken = SessionTokenUtils.createToken(userDetails.getUsername(), timeout);
                    httpSession.setAttribute(STUDIO_SESSION_TOKEN_ATRIBUTE, newToken);
                }
            } else {
                crafterLogger.debug("Session is not valid. Clearing HttpSession");
                httpSession.removeAttribute(STUDIO_SESSION_TOKEN_ATRIBUTE);
                httpSession.invalidate();
            }
        } else {
            if (isAuthenticationHeadersEnabled()) {
                // If user not authenticated check for authentication headers
                String usernameHeader = httpRequest
                        .getHeader(studioConfiguration.getProperty(AUTHENTICATION_HEADERS_USERNAME));
                try {
                    securityService.authenticate(usernameHeader, RandomStringUtils.randomAlphanumeric(16));
                    UserDetails userDetails = this.userDetailsManager.loadUserByUsername(usernameHeader);
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                            userDetails, null, userDetails.getAuthorities());
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                } catch (BadCredentialsException | AuthenticationSystemException e) {
                    crafterLogger.error("Unable to authenticate user using authentication headers.");
                }
            }
        }
    } finally {
        semaphore.unlock();
    }
    filterChain.doFilter(servletRequest, servletResponse);
}

From source file:org.apache.wicket.protocol.http.mock.MockHttpServletRequest.java

@Override
public String changeSessionId() {
    final HttpSession oldSession = getSession(false);
    if (oldSession == null) {
        throw new IllegalStateException("There is no active session associated with the current request");
    }/*  w w  w .  j  ava2  s  .c  o  m*/
    oldSession.invalidate();

    final HttpSession newSession = getSession(true);

    return newSession.getId();
}

From source file:com.tecapro.inventory.common.action.BaseAction.java

/**
 * Check action with session/*from ww  w  .  j a  v  a  2  s. c  om*/
 *
 * @param form
 * @param request
 * @param mapping
 */
private void changeSession(BaseForm form, HttpServletRequest request, ActionMapping mapping) {
    String param = mapping.getParameter();

    if (param != null && param.contains(PARAM_CREATE_SESSION)) {
        // new HTTPSession
        HttpSession session = request.getSession(true);
        session.setAttribute(Constants.SESSION_INFO, form.getValue().getInfo().getMainSessInfo());
        userInfo = new UserInfoValue();

    } else if (param != null
            && (param.contains(PARAM_INVALIDATE_SESSION) || param.contains(PARAM_NO_SESSION))) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.removeAttribute(Constants.SESSION_INFO);
            session.invalidate();
        }
        userInfo = new UserInfoValue();
    } else {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.setAttribute(Constants.SESSION_INFO, form.getValue().getInfo().getMainSessInfo());
        }
    }

}

From source file:org.alfresco.repo.webdav.auth.BaseAuthenticationFilter.java

/**
 * Callback to get the specific impl of the Session User for a filter.
 * /*from   w ww .j a v  a 2 s  .c om*/
 * @param servletContext
 *            the servlet context
 * @param httpServletRequest
 *            the http servlet request
 * @param httpServletResponse
 *            the http servlet response
 * @param externalAuth
 *            has the user been authenticated by SSO?
 * @return User from the session
 */
protected SessionUser getSessionUser(ServletContext servletContext, final HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse, final boolean externalAuth) {
    String userId = null;

    // If the remote user mapper is configured, we may be able to map in an externally authenticated user
    if (remoteUserMapper != null && (!(remoteUserMapper instanceof ActivateableBean)
            || ((ActivateableBean) remoteUserMapper).isActive())) {
        userId = remoteUserMapper.getRemoteUser(httpServletRequest);
        if (getLogger().isDebugEnabled())
            getLogger().debug("Found a remote user: " + userId);
    }

    String sessionAttrib = getUserAttributeName();
    HttpSession session = httpServletRequest.getSession();
    SessionUser sessionUser = (SessionUser) session.getAttribute(sessionAttrib);
    if (sessionUser != null) {
        try {
            if (getLogger().isDebugEnabled())
                getLogger().debug("Found a session user: " + sessionUser.getUserName());
            authenticationService.validate(sessionUser.getTicket());
            setExternalAuth(session, externalAuth);
        } catch (AuthenticationException e) {
            if (getLogger().isDebugEnabled())
                getLogger().debug(
                        "The ticket may have expired or the person could have been removed, invalidating session.",
                        e);
            invalidateSession(httpServletRequest);
            sessionUser = null;
        }
    }

    if (userId != null) {
        if (getLogger().isDebugEnabled())
            getLogger().debug("We have a previously-cached user with the wrong identity - replace them.");
        if (sessionUser != null && !sessionUser.getUserName().equals(userId)) {
            if (getLogger().isDebugEnabled())
                getLogger().debug("Removing the session user, invalidating session.");
            session.removeAttribute(sessionAttrib);
            session.invalidate();
            sessionUser = null;
        }

        if (sessionUser == null) {
            // If we have been authenticated by other means, just propagate through the user identity
            if (getLogger().isDebugEnabled())
                getLogger().debug("Propagating through the user identity: " + userId);
            authenticationComponent.setCurrentUser(userId);
            session = httpServletRequest.getSession();

            try {
                sessionUser = createUserEnvironment(session, authenticationService.getCurrentUserName(),
                        authenticationService.getCurrentTicket(), true);
            } catch (Throwable e) {
                if (getLogger().isDebugEnabled())
                    getLogger().debug("Error during ticket validation and user creation: " + e.getMessage(), e);
            }
        }
    }

    return sessionUser;
}

From source file:net.java.jaspicoil.MSPacSpnegoServerAuthModule.java

/**
 * Authenticate a received service request.
 * <p/>/*from w  ww  . j a  v a 2s  . c  o  m*/
 * This method is called to transform the mechanism-specific request message
 * acquired by calling getRequestMessage (on messageInfo) into the validated
 * application message to be returned to the message processing runtime. If
 * the received message is a (mechanism-specific) meta-message, the method
 * implementation must attempt to transform the meta-message into a
 * corresponding mechanism-specific response message, or to the validated
 * application request message. The runtime will bind a validated
 * application message into the the corresponding service invocation.
 * <p>
 * This method conveys the outcome of its message processing either by
 * returning an AuthStatus value or by throwing an AuthException.
 * <p/>
 * From a performance point of view this method will be called twice for
 * each resource with a security constraint on it. Resources with no
 * security constraint do not result in a call to this method.
 * 
 * @param messageInfo
 *            A contextual object that encapsulates the client request and
 *            server response objects, and that may be used to save state
 *            across a sequence of calls made to the methods of this
 *            interface for the purpose of completing a secure message
 *            exchange.
 * @param clientSubject
 *            A Subject that represents the source of the service request.
 *            It is used by the method implementation to store Principals
 *            and credentials validated in the request.
 * @param serviceSubject
 *            A Subject that represents the recipient of the service
 *            request, or null. It may be used by the method implementation
 *            as the source of Principals or credentials to be used to
 *            validate the request. If the Subject is not null, the method
 *            implementation may add additional Principals or credentials
 *            (pertaining to the recipient of the service request) to the
 *            Subject.
 * @return An AuthStatus object representing the completion status of the
 *         processing performed by the method. The AuthStatus values that
 *         may be returned by this method are defined as follows:
 *         <p/>
 *         <ul>
 *         <li>AuthStatus.SUCCESS when the application request message was
 *         successfully validated. The validated request message is
 *         available by calling getRequestMessage on messageInfo.
 *         <p/>
 *         <li>AuthStatus.SEND_SUCCESS to indicate that
 *         validation/processing of the request message successfully
 *         produced the secured application response message (in
 *         messageInfo). The secured response message is available by
 *         calling getResponseMessage on messageInfo.
 *         <p/>
 *         <li>AuthStatus.SEND_CONTINUE to indicate that message validation
 *         is incomplete, and that a preliminary response was returned as
 *         the response message in messageInfo.
 *         <p/>
 *         When this status value is returned to challenge an application
 *         request message, the challenged request must be saved by the
 *         authentication module such that it can be recovered when the
 *         module's validateRequest message is called to process the request
 *         returned for the challenge.
 *         <p/>
 *         <li>AuthStatus.SEND_FAILURE to indicate that message validation
 *         failed and that an appropriate failure response message is
 *         available by calling getResponseMessage on messageInfo.
 *         </ul>
 * @throws AuthException When the message processing failed without
 *         establishing a failure response message (in messageInfo).
 */
@SuppressWarnings("unchecked")
public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject)
        throws AuthException {

    // Extra check (disabled withour -ea) if mandatory value is consistent
    // with initialize phase
    assert messageInfo.getMap().containsKey(IS_MANDATORY_INFO_KEY) == this.mandatory;

    // Get the servlet context
    final HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage();
    final HttpServletResponse response = (HttpServletResponse) messageInfo.getResponseMessage();

    // Invalidate any existing session to prevent session fixture attempt
    HttpSession session = request.getSession(false);
    if (session != null) {
        final SessionState state = (SessionState) session.getAttribute(MAGIC_SESSION_STATE_KEY);
        if (state == null) {
            // Session was not created by us, we will invalidate an existing
            // session that was not created by us
            session.invalidate();
            LOG.warning(
                    "An existing session was invalidated. This might be a session fixture attempt, so failing the authentication.");
            return AuthStatus.SEND_FAILURE;
        } else if (SessionState.ESTABLISHED.equals(state)) {
            // The context was already fully established once within this
            // session.
            return AuthStatus.SUCCESS;
        }
    }

    debugRequest(request);

    // should specify encoder
    final String authorization = request.getHeader(AUTHORIZATION_HEADER);

    if (authorization != null && authorization.startsWith(NEGOTIATE)) {

        final String negotiateString = authorization.substring(NEGOTIATE.length() + 1);

        final byte[] requestToken = Base64.decodeBase64(negotiateString);

        if (serviceSubject == null) {
            // If no service subject was provided by the container then set
            // a service subject
            // from the global context.
            serviceSubject = this.serviceSubject;
        }

        try {
            // Create a validation action
            byte[] gssToken = null;
            final KerberosValidateAction kva = new KerberosValidateAction(this.servicePrincipal, requestToken,
                    serviceSubject);
            try {
                // Validate using the service (server) Subject
                gssToken = Subject.doAs(this.serviceSubject, kva);
            } catch (final PrivilegedActionException e) {
                final GSSException gex = new GSSException(GSSException.DEFECTIVE_TOKEN);
                gex.initCause(e);
                gex.setMinor(GSSException.UNAVAILABLE, "Unable to perform Kerberos validation");
                throw gex;
            }

            if (kva.getContext() != null) {
                final String responseToken = Base64.encodeBase64String(gssToken);
                response.setHeader(AUTHENTICATION_HEADER, "Negotiate " + responseToken);
                debugToken("GSS Response token set to {0}", gssToken);
            }

            if (!kva.isEstablished()) {
                debug("GSS Dialog must continue to succeed");

                session.setAttribute(MAGIC_SESSION_STATE_KEY, SessionState.IN_PROGRESS);

                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return AuthStatus.SEND_CONTINUE;

            } else {

                final Oid mechId = kva.getMech();
                final GSSName name = kva.getSrcName();

                if (!authorizeCaller(request, requestToken, name, clientSubject)) {
                    return sendFailureMessage(response, "Failed to authorize the caller/client");
                }

                // As no valid session should exist anymore, simply create a
                // new one
                session = request.getSession(true);

                final Principal clientPrincipal = new KerberosPrincipal(
                        name.canonicalize(GSS_KRB5_MECH_OID).toString());

                updateSessionAndHeader(request, session, clientPrincipal);

                session.setAttribute(MAGIC_SESSION_STATE_KEY, SessionState.ESTABLISHED);
                /*
                 * Store the mechId in the MessageInfo to indicate which
                 * authentication mechanism was used successfully (JASPIC
                 * Requirement)
                 */
                messageInfo.getMap().put(AUTH_TYPE_INFO_KEY,
                        mechId != null ? mechId.toString() : "Undefined GSS Mechanism");

                debug("GSS Dialog is complete");

            }

        } catch (final GSSException gsse) {
            debug("GSS Dialog has failed : {0}", gsse);

            if (requestToken != null) {
                debug("Bad token detected {0}", gsse);
                debugToken("Bad token was {0}", requestToken);

                if (isNTLMToken(requestToken)) {
                    // There is a high probability it was a NTLM SPNEGO
                    // token
                    return sendFailureMessage(response, "No support for NTLM");
                }
            }

            // for other errors throw an AuthException
            final AuthException ae = new AuthException();
            ae.initCause(gsse);
            throw ae;
        }

    } else if (this.mandatory) {

        response.setHeader(AUTHENTICATION_HEADER, NEGOTIATE);
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        debug("Negotiate was added to the HTTP header : {0}", NEGOTIATE);

        return AuthStatus.SEND_CONTINUE;

    } else if (authorization != null) {
        LOG.warning("An authorization header was ignored.");
    }

    return AuthStatus.SUCCESS;
}

From source file:org.wso2.carbon.core.services.authentication.AuthenticationAdmin.java

public void logout() throws AuthenticationException {
    String loggedInUser;/*  w w w . j a v  a2  s .co  m*/
    String delegatedBy;
    String tenantDomain;
    int tenantId;
    Date currentTime = Calendar.getInstance().getTime();
    SimpleDateFormat date = new SimpleDateFormat("'['yyyy-MM-dd HH:mm:ss,SSSS']'");
    HttpSession session = getHttpSession();

    if (session != null) {
        loggedInUser = (String) session.getAttribute(ServerConstants.USER_LOGGED_IN);
        delegatedBy = (String) session.getAttribute("DELEGATED_BY");
        tenantDomain = (String) session.getAttribute(MultitenantConstants.TENANT_DOMAIN);
        try {
            tenantId = CarbonServicesServiceComponent.getRealmService().getTenantManager()
                    .getTenantId(tenantDomain);
        } catch (Exception e) {
            //setting to invalid tenant id because we couldn't get the tenant id
            tenantId = MultitenantConstants.INVALID_TENANT_ID;
            log.error(e.getMessage(), e);
            throw new AuthenticationException(e);
        }
        if (delegatedBy == null && loggedInUser != null) {
            String logMsg = "'" + loggedInUser + "@" + tenantDomain + " [" + tenantId + "]' logged out at "
                    + date.format(currentTime);
            log.info(logMsg);
            audit.info(logMsg);
        } else if (loggedInUser != null) {
            String logMsg = "'" + loggedInUser + "@" + tenantDomain + " [" + tenantId + "]' logged out at "
                    + date.format(currentTime) + " delegated by " + delegatedBy;
            log.info(logMsg);
            audit.info(logMsg);
        }
        //We should not invalidate the session if the system is running on local transport
        if (!isRequestedFromLocalTransport()) {
            session.invalidate();
        }
    }
}

From source file:org.ofbiz.order.shoppingcart.ShoppingCartEvents.java

/** Empty the shopping cart. */
public static String clearCart(HttpServletRequest request, HttpServletResponse response) {
    ShoppingCart cart = getCartObject(request);
    cart.clear();/*from ww w.  j a v  a  2 s .c o  m*/

    // if this was an anonymous checkout process, go ahead and clear the session and such now that the order is placed; we don't want this to mess up additional orders and such
    HttpSession session = request.getSession();
    GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
    if (userLogin != null && "anonymous".equals(userLogin.get("userLoginId"))) {
        // here we want to do a full logout, but not using the normal logout stuff because it saves things in the UserLogin record that we don't want changed for the anonymous user
        session.invalidate();
        session = request.getSession(true);

        // to allow the display of the order confirmation page put the userLogin in the request, but leave it out of the session
        request.setAttribute("temporaryAnonymousUserLogin", userLogin);

        Debug.logInfo(
                "Doing clearCart for anonymous user, so logging out but put anonymous userLogin in temporaryAnonymousUserLogin request attribute",
                module);
    }

    return "success";
}

From source file:org.apache.tapestry.engine.AbstractEngine.java

/**
 * Invalidates the session, then redirects the client web browser to
 * the servlet's prefix, starting a new visit.
 *
 * <p>Subclasses should perform their own restart (if necessary, which is
 * rarely) before invoking this implementation.
 *
 **///from   w w w.  ja v a 2s.  c  o m

public void restart(IRequestCycle cycle) throws IOException {
    RequestContext context = cycle.getRequestContext();

    HttpSession session = context.getSession();

    if (session != null) {
        try {
            session.invalidate();
        } catch (IllegalStateException ex) {
            if (LOG.isDebugEnabled())
                LOG.debug("Exception thrown invalidating HttpSession.", ex);

            // Otherwise, ignore it.
        }
    }

    // Make isStateful() return false, so that the servlet doesn't
    // try to store the engine back into the (now invalid) session.

    _stateful = false;

    String url = context.getAbsoluteURL(_servletPath);

    context.redirect(url);
}