Search in sources :

Example 66 with Session

use of org.apache.catalina.Session in project tomcat70 by apache.

the class StandardManager method stopInternal.

/**
 * Stop this component and implement the requirements
 * of {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
 *
 * @exception LifecycleException if this component detects a fatal error
 *  that prevents this component from being used
 */
@Override
protected synchronized void stopInternal() throws LifecycleException {
    if (log.isDebugEnabled()) {
        log.debug("Stopping");
    }
    setState(LifecycleState.STOPPING);
    // Write out sessions
    try {
        unload();
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        log.error(sm.getString("standardManager.managerUnload"), t);
    }
    // Expire all active sessions
    Session[] sessions = findSessions();
    for (int i = 0; i < sessions.length; i++) {
        Session session = sessions[i];
        try {
            if (session.isValid()) {
                session.expire();
            }
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
        } finally {
            // Measure against memory leaking if references to the session
            // object are kept in a shared field somewhere
            session.recycle();
        }
    }
    // Require a new random number generator if we are restarted
    super.stopInternal();
}
Also used : Session(org.apache.catalina.Session)

Example 67 with Session

use of org.apache.catalina.Session in project tomcat70 by apache.

the class StandardManager method doUnload.

/**
 * Save any currently active sessions in the appropriate persistence
 * mechanism, if any.  If persistence is not supported, this method
 * returns without doing anything.
 *
 * @exception IOException if an input/output error occurs
 */
protected void doUnload() throws IOException {
    if (log.isDebugEnabled())
        log.debug(sm.getString("standardManager.unloading.debug"));
    if (sessions.isEmpty()) {
        log.debug(sm.getString("standardManager.unloading.nosessions"));
        // nothing to do
        return;
    }
    // Open an output stream to the specified pathname, if any
    File file = file();
    if (file == null) {
        return;
    }
    if (log.isDebugEnabled()) {
        log.debug(sm.getString("standardManager.unloading", pathname));
    }
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
    ObjectOutputStream oos = null;
    boolean error = false;
    try {
        fos = new FileOutputStream(file.getAbsolutePath());
        bos = new BufferedOutputStream(fos);
        oos = new ObjectOutputStream(bos);
    } catch (IOException e) {
        error = true;
        log.error(sm.getString("standardManager.unloading.ioe", e), e);
        throw e;
    } finally {
        if (error) {
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException ioe) {
                // Ignore
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException ioe) {
                // Ignore
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ioe) {
                // Ignore
                }
            }
        }
    }
    // Write the number of active sessions, followed by the details
    ArrayList<StandardSession> list = new ArrayList<StandardSession>();
    synchronized (sessions) {
        if (log.isDebugEnabled()) {
            log.debug("Unloading " + sessions.size() + " sessions");
        }
        try {
            oos.writeObject(Integer.valueOf(sessions.size()));
            Iterator<Session> elements = sessions.values().iterator();
            while (elements.hasNext()) {
                StandardSession session = (StandardSession) elements.next();
                list.add(session);
                session.passivate();
                session.writeObjectData(oos);
            }
        } catch (IOException e) {
            log.error(sm.getString("standardManager.unloading.ioe", e), e);
            try {
                oos.close();
            } catch (IOException f) {
            // Ignore
            }
            throw e;
        }
    }
    // Flush and close the output stream
    try {
        oos.flush();
    } finally {
        try {
            oos.close();
        } catch (IOException f) {
        // Ignore
        }
    }
    // Expire all the sessions we just wrote
    if (log.isDebugEnabled()) {
        log.debug("Expiring " + list.size() + " persisted sessions");
    }
    Iterator<StandardSession> expires = list.iterator();
    while (expires.hasNext()) {
        StandardSession session = expires.next();
        try {
            session.expire(false);
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
        } finally {
            session.recycle();
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Unloading complete");
    }
}
Also used : ArrayList(java.util.ArrayList) IOException(java.io.IOException) ObjectOutputStream(java.io.ObjectOutputStream) FileOutputStream(java.io.FileOutputStream) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream) Session(org.apache.catalina.Session)

Example 68 with Session

use of org.apache.catalina.Session in project Payara by payara.

the class WebProgrammaticLoginImpl method logout.

/**
 * Logout and remove principal in request and session.
 *
 * @param request HTTP request object provided by caller application. It should be an instance of HttpRequestFacade.
 * @param response HTTP response object provided by called application. It should be an instance of HttpServletResponse.
 * This is not used currently.
 * @returns A Boolean object; true if login succeeded, false otherwise.
 * @see com.sun.enterprise.security.ee.auth.login.ProgrammaticLogin
 * @throws Exception any exception encountered during logout operation
 */
@Override
public Boolean logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
    // Need real request object not facade
    Request unwrappedCoyoteRequest = getUnwrappedCoyoteRequest(request);
    if (unwrappedCoyoteRequest == null) {
        return false;
    }
    // Logout - clears out security context
    WebAndEjbToJaasBridge.logout();
    // Remove principal and auth type from request
    unwrappedCoyoteRequest.setUserPrincipal(null);
    unwrappedCoyoteRequest.setAuthType(null);
    logger.fine("Programmatic logout removed principal from request.");
    // Remove from session if possible.
    Session realSession = getSession(unwrappedCoyoteRequest);
    if (realSession != null) {
        realSession.setPrincipal(null);
        realSession.setAuthType(null);
        if (logger.isLoggable(FINE)) {
            logger.log(FINE, "Programmatic logout removed principal from " + "session.");
        }
    }
    return true;
}
Also used : Request(org.apache.catalina.connector.Request) ServletRequest(javax.servlet.ServletRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpSession(javax.servlet.http.HttpSession) Session(org.apache.catalina.Session)

Example 69 with Session

use of org.apache.catalina.Session in project Payara by payara.

the class FormAuthenticator method authenticate.

// ------------------------------------------------------- Public Methods
/**
 * Authenticate the user making this request, based on the specified login configuration. Return <code>true</code> if
 * any specified constraint has been satisfied, or <code>false</code> if we have created a response challenge already.
 *
 * @param request Request we are processing
 * @param response Response we are creating
 * @param config Login configuration describing how authentication should be performed
 *
 * @exception IOException if an input/output error occurs
 */
@Override
public boolean authenticate(HttpRequest request, HttpResponse response, LoginConfig config) throws IOException {
    // References to objects we will need later
    HttpServletRequest hreq = (HttpServletRequest) request.getRequest();
    HttpServletResponse hres = (HttpServletResponse) response.getResponse();
    Session session = null;
    String contextPath = hreq.getContextPath();
    String requestURI = request.getDecodedRequestURI();
    // Is this the action request from the login page?
    boolean loginAction = requestURI.startsWith(contextPath) && requestURI.endsWith(FORM_ACTION);
    if (loginAction && !isPermittedHttpMethod(hreq.getMethod())) {
        hres.sendError(SC_FORBIDDEN, rb.getString(LogFacade.ACCESS_RESOURCE_DENIED));
        return false;
    }
    // Have we already authenticated someone?
    Principal principal = hreq.getUserPrincipal();
    // processing section of this method.
    if (principal != null && !loginAction) {
        if (log.isLoggable(FINE)) {
            log.log(FINE, "Already authenticated '" + principal.getName() + "'");
        }
        String ssoId = (String) request.getNote(REQ_SSOID_NOTE);
        if (ssoId != null) {
            getSession(request, true);
        }
        return true;
    }
    // processing section of this method.
    if (!cache && !loginAction) {
        session = getSession(request, true);
        if (log.isLoggable(Level.FINE)) {
            log.log(Level.FINE, "Checking for reauthenticate in session " + session);
        }
        String username = (String) session.getNote(SESS_USERNAME_NOTE);
        char[] password = (char[]) session.getNote(SESS_PASSWORD_NOTE);
        if ((username != null) && (password != null)) {
            if (log.isLoggable(FINE)) {
                log.log(FINE, "Reauthenticating username '" + username + "'");
            }
            principal = context.getRealm().authenticate(username, password);
            if (principal != null) {
                session.setNote(FORM_PRINCIPAL_NOTE, principal);
                if (!matchRequest(request)) {
                    register(request, response, principal, FORM_METHOD, username, password);
                    return true;
                }
            }
            if (log.isLoggable(FINE)) {
                log.log(Level.FINE, "Reauthentication failed, proceed normally");
            }
        }
    }
    // authentication? If so, forward the *original* request instead.
    if (matchRequest(request)) {
        session = getSession(request, true);
        if (log.isLoggable(FINE)) {
            log.log(FINE, "Restore request from session '" + session.getIdInternal() + "'");
        }
        principal = (Principal) session.getNote(FORM_PRINCIPAL_NOTE);
        register(request, response, principal, FORM_METHOD, (String) session.getNote(SESS_USERNAME_NOTE), (char[]) session.getNote(SESS_PASSWORD_NOTE));
        String ssoId = (String) request.getNote(REQ_SSOID_NOTE);
        if (ssoId != null) {
            associate(ssoId, getSsoVersion(request), session);
        }
        if (restoreRequest(request, session)) {
            log.fine("Proceed to restored request");
            return true;
        }
        log.fine("Restore of original request failed");
        hres.sendError(SC_BAD_REQUEST);
        return false;
    }
    // Acquire references to objects we will need to evaluate
    CharChunk uriCC = MessageBytes.newInstance().getCharChunk();
    uriCC.setLimit(-1);
    response.setContext(request.getContext());
    // No -- Save this request and redirect to the form login page
    if (!loginAction) {
        session = getSession(request, true);
        if (log.isLoggable(FINE)) {
            log.log(FINE, "Save request in session '" + session.getIdInternal() + "'");
        }
        saveRequest(request, session);
        forwardToLoginPage(request, response, config);
        return false;
    }
    // Yes -- Validate the specified credentials and redirect
    // to the error page if they are not correct
    Realm realm = context.getRealm();
    String username = hreq.getParameter(FORM_USERNAME);
    String pwd = hreq.getParameter(FORM_PASSWORD);
    char[] password = pwd != null ? pwd.toCharArray() : null;
    if (log.isLoggable(FINE)) {
        log.log(FINE, "Authenticating username '" + username + "'");
    }
    principal = realm.authenticate(username, password);
    if (principal == null) {
        forwardToErrorPage(request, response, config);
        return false;
    }
    // Save the authenticated Principal in our session
    if (log.isLoggable(FINE)) {
        log.log(FINE, "Authentication of '" + username + "' was successful");
    }
    if (session == null) {
        session = getSession(request, true);
    }
    session.setNote(FORM_PRINCIPAL_NOTE, principal);
    // If we are not caching, save the username and password as well
    if (!cache) {
        session.setNote(SESS_USERNAME_NOTE, username);
        session.setNote(SESS_PASSWORD_NOTE, password);
    }
    // Redirect the user to the original request URI (which will cause
    // the original request to be restored)
    requestURI = savedRequestURL(session);
    if (requestURI == null) {
        // requestURI will be null if the login form is submitted directly, i.e., if there has not been any original request
        // that was stored away before the redirect to the login form was issued. In this case, assume that the original request has been
        // for the context root, and have the welcome page mechanism take care of it
        requestURI = hreq.getContextPath() + "/";
        register(request, response, principal, FORM_METHOD, (String) session.getNote(SESS_USERNAME_NOTE), (char[]) session.getNote(SESS_PASSWORD_NOTE));
        String ssoId = (String) request.getNote(REQ_SSOID_NOTE);
        if (ssoId != null) {
            associate(ssoId, getSsoVersion(request), session);
        }
    }
    if (log.isLoggable(Level.FINE)) {
        log.log(Level.FINE, "Redirecting to original '" + requestURI + "'");
    }
    hres.sendRedirect(hres.encodeRedirectURL(requestURI));
    return false;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) Realm(org.apache.catalina.Realm) Principal(java.security.Principal) CharChunk(org.glassfish.grizzly.http.util.CharChunk) Session(org.apache.catalina.Session)

Example 70 with Session

use of org.apache.catalina.Session in project Payara by payara.

the class FormAuthenticator method matchRequest.

/**
 * Does this request match the saved one (so that it must be the redirect we signaled after successful authentication?
 *
 * @param request The request to be verified
 */
protected boolean matchRequest(HttpRequest request) {
    // Has a session been created?
    Session session = getSession(request, false);
    if (session == null) {
        return false;
    }
    // Is there a saved request?
    SavedRequest savedRequest = (SavedRequest) session.getNote(FORM_REQUEST_NOTE);
    if (savedRequest == null) {
        return false;
    }
    // Is there a saved principal?
    if (session.getNote(Constants.FORM_PRINCIPAL_NOTE) == null) {
        return false;
    }
    // Does the request URI match?
    HttpServletRequest httpServletRequest = (HttpServletRequest) request.getRequest();
    String requestURI = httpServletRequest.getRequestURI();
    if (requestURI == null) {
        return false;
    }
    return requestURI.equals(savedRequest.getRequestURI());
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Session(org.apache.catalina.Session)

Aggregations

Session (org.apache.catalina.Session)106 IOException (java.io.IOException)24 Manager (org.apache.catalina.Manager)22 Context (org.apache.catalina.Context)16 HttpSession (javax.servlet.http.HttpSession)13 StringManager (org.apache.tomcat.util.res.StringManager)13 HttpServletRequest (javax.servlet.http.HttpServletRequest)9 HttpSession (jakarta.servlet.http.HttpSession)7 GenericPrincipal (org.apache.catalina.realm.GenericPrincipal)7 Principal (java.security.Principal)6 Realm (org.apache.catalina.Realm)6 StandardContext (org.apache.catalina.core.StandardContext)6 ClusterSession (org.apache.catalina.ha.ClusterSession)6 DeltaSession (org.apache.catalina.ha.session.DeltaSession)6 Container (org.apache.catalina.Container)5 ArrayList (java.util.ArrayList)4 StandardSession (org.apache.catalina.session.StandardSession)4 BufferedOutputStream (java.io.BufferedOutputStream)3 File (java.io.File)3 ObjectOutputStream (java.io.ObjectOutputStream)3