Java Code Examples for org.apache.catalina.connector.Request#getSessionInternal()

The following examples show how to use org.apache.catalina.connector.Request#getSessionInternal() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ReplicationValve.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Send Cluster Replication Request
 * @param request current request
 * @param manager session manager
 */
protected void sendSessionReplicationMessage(Request request,
        ClusterManager manager) {
    Session session = request.getSessionInternal(false);
    if (session != null) {
        String uri = request.getDecodedRequestURI();
        // request without session change
        if (!isRequestWithoutSessionChange(uri)) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("ReplicationValve.invoke.uri", uri));
            }
            sendMessage(session,manager);
        } else
            if(doStatistics()) {
                nrOfFilterRequests++;
            }
    }

}
 
Example 2
Source File: FederationAuthenticator.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
protected boolean validateToken(Request request, HttpServletResponse response, FedizContext fedConfig) {
    Session session = request.getSessionInternal();
    if (session != null) {

        FedizResponse wfRes = (FedizResponse)session.getNote(FEDERATION_NOTE);
        Instant tokenExpires = wfRes.getTokenExpires();
        if (tokenExpires == null) {
            LOG.debug("Token doesn't expire");
            return true;
        }

        Instant currentTime = Instant.now();
        if (!currentTime.isAfter(tokenExpires)) {
            return true;
        } else {
            LOG.warn("Token already expired. Clean up and redirect");

            session.removeNote(FEDERATION_NOTE);
            session.setPrincipal(null);
            request.getSession().removeAttribute(SECURITY_TOKEN);
        }
    } else {
        LOG.debug("Session should not be null after authentication");
    }
    return false;
}
 
Example 3
Source File: ReplicationValve.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Send Cluster Replication Request
 * @param request current request
 * @param manager session manager
 * @param cluster replication cluster
 */
protected void sendSessionReplicationMessage(Request request,
        ClusterManager manager, CatalinaCluster cluster) {
    Session session = request.getSessionInternal(false);
    if (session != null) {
        String uri = request.getDecodedRequestURI();
        // request without session change
        if (!isRequestWithoutSessionChange(uri)) {
            if (log.isDebugEnabled())
                log.debug(sm.getString("ReplicationValve.invoke.uri", uri));
            sendMessage(session,manager,cluster);
        } else
            if(doStatistics())
                nrOfFilterRequests++;
    }

}
 
Example 4
Source File: ReplicationValve.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Fix memory leak for long sessions with many changes, when no backup member exists!
 * @param request current request after response is generated
 * @param isCrossContext check crosscontext threadlocal
 */
protected void resetReplicationRequest(Request request, boolean isCrossContext) {
    Session contextSession = request.getSessionInternal(false);
    if(contextSession instanceof DeltaSession){
        resetDeltaRequest(contextSession);
        ((DeltaSession)contextSession).setPrimarySession(true);
    }
    if(isCrossContext) {
        List<DeltaSession> sessions = crossContextSessions.get();
        if(sessions != null && sessions.size() >0) {
            Iterator<DeltaSession> iter = sessions.iterator();
            for(; iter.hasNext() ;) {          
                Session session = iter.next();
                resetDeltaRequest(session);
                if(session instanceof DeltaSession)
                    ((DeltaSession)contextSession).setPrimarySession(true);

            }
        }
    }                     
}
 
Example 5
Source File: ReplicationValve.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Fix memory leak for long sessions with many changes, when no backup member exists!
 * @param request current request after response is generated
 * @param isCrossContext check crosscontext threadlocal
 */
protected void resetReplicationRequest(Request request, boolean isCrossContext) {
    Session contextSession = request.getSessionInternal(false);
    if(contextSession instanceof DeltaSession){
        resetDeltaRequest(contextSession);
        ((DeltaSession)contextSession).setPrimarySession(true);
    }
    if(isCrossContext) {
        List<DeltaSession> sessions = crossContextSessions.get();
        if(sessions != null && sessions.size() >0) {
            Iterator<DeltaSession> iter = sessions.iterator();
            for(; iter.hasNext() ;) {          
                Session session = iter.next();
                resetDeltaRequest(session);
                if(session instanceof DeltaSession)
                    ((DeltaSession)contextSession).setPrimarySession(true);

            }
        }
    }                     
}
 
Example 6
Source File: FederationAuthenticator.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
protected void saveRequest(Request request, RequestState requestState) throws IOException {
    String contextId = requestState.getState();
    String uri = request.getDecodedRequestURI();
    Session session = request.getSessionInternal(true);
    if (session != null) {
        LOG.debug("Save request in session '{}'", session.getIdInternal());
    }
    if (session != null && uri != null) {
        SavedRequest saved;
        synchronized (session) {
            super.saveRequest(request, session);
            saved = (SavedRequest) session.getNote(Constants.FORM_REQUEST_NOTE);
        }
        session.setNote(SESSION_SAVED_REQUEST_PREFIX + uri, saved);
        StringBuilder sb = new StringBuilder(saved.getRequestURI());
        if (saved.getQueryString() != null) {
            sb.append('?');
            sb.append(saved.getQueryString());
        }
        session.setNote(SESSION_SAVED_URI_PREFIX + contextId, sb.toString());
        //we set Request State as session attribute for later retrieval in SigninHandler
        request.getSession().setAttribute(
            FederationConstants.SESSION_SAVED_REQUEST_STATE_PREFIX + requestState.getState(), requestState);
    }
}
 
Example 7
Source File: ReplicationValve.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Fix memory leak for long sessions with many changes, when no backup member exists!
 * @param request current request after response is generated
 * @param isCrossContext check crosscontext threadlocal
 */
protected void resetReplicationRequest(Request request, boolean isCrossContext) {
    Session contextSession = request.getSessionInternal(false);
    if(contextSession instanceof DeltaSession){
        resetDeltaRequest(contextSession);
        ((DeltaSession)contextSession).setPrimarySession(true);
    }
    if(isCrossContext) {
        List<DeltaSession> sessions = crossContextSessions.get();
        if(sessions != null && sessions.size() >0) {
            Iterator<DeltaSession> iter = sessions.iterator();
            for(; iter.hasNext() ;) {
                Session session = iter.next();
                resetDeltaRequest(session);
                if(session instanceof DeltaSession) {
                    ((DeltaSession)contextSession).setPrimarySession(true);
                }

            }
        }
    }
}
 
Example 8
Source File: FederationAuthenticator.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
protected boolean restoreRequest(Request request) throws IOException {
    Session session = request.getSessionInternal(false);
    String uri = request.getDecodedRequestURI();
    if (session != null && uri != null) {
        SavedRequest saved = (SavedRequest)session.getNote(SESSION_SAVED_REQUEST_PREFIX + uri);
        if (saved != null) {
            session.removeNote(SESSION_SAVED_REQUEST_PREFIX + uri); // cleanup session
            synchronized (session) {
                session.setNote(Constants.FORM_REQUEST_NOTE, saved);
                return super.restoreRequest(request, session);
            }
        }
    }
    return false;
}
 
Example 9
Source File: FormAuthenticator.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * 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(Request request) {

  // Has a session been created?
  Session session = request.getSessionInternal(false);
  if (session == null) {
    return (false);
}

  // Is there a saved request?
  SavedRequest sreq = (SavedRequest)
      session.getNote(Constants.FORM_REQUEST_NOTE);
  if (sreq == null) {
    return (false);
}

  // Is there a saved principal?
  if (session.getNote(Constants.FORM_PRINCIPAL_NOTE) == null) {
    return (false);
}

  // Does the request URI match?
  String decodedRequestURI = request.getDecodedRequestURI();
  if (decodedRequestURI == null) {
    return (false);
}
  return (decodedRequestURI.equals(sreq.getDecodedRequestURI()));
}
 
Example 10
Source File: AccessLogValve.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Override
public void addElement(StringBuilder buf, Date date, Request request,
        Response response, long time) {
    if (request == null) {
        buf.append('-');
    } else {
        Session session = request.getSessionInternal(false);
        if (session == null) {
            buf.append('-');
        } else {
            buf.append(session.getIdInternal());
        }
    }
}
 
Example 11
Source File: FormAuthenticator.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * 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
 * @return <code>true</code> if the requests matched the saved one
 */
protected boolean matchRequest(Request request) {
    // Has a session been created?
    Session session = request.getSessionInternal(false);
    if (session == null) {
        return false;
    }

    // Is there a saved request?
    SavedRequest sreq =
            (SavedRequest) session.getNote(Constants.FORM_REQUEST_NOTE);
    if (sreq == null) {
        return false;
    }

    // Is there a saved principal?
    if (session.getNote(Constants.FORM_PRINCIPAL_NOTE) == null) {
        return false;
    }

    // Does the request URI match?
    String decodedRequestURI = request.getDecodedRequestURI();
    if (decodedRequestURI == null) {
        return false;
    }
    return decodedRequestURI.equals(sreq.getDecodedRequestURI());
}
 
Example 12
Source File: FormAuthenticator.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
protected boolean isContinuationRequired(Request request) {
    // Special handling for form-based logins to deal with the case
    // where the login form (and therefore the "j_security_check" URI
    // to which it submits) might be outside the secured area
    String contextPath = this.context.getPath();
    String decodedRequestURI = request.getDecodedRequestURI();
    if (decodedRequestURI.startsWith(contextPath) &&
            decodedRequestURI.endsWith(Constants.FORM_ACTION)) {
        return true;
    }

    // Special handling for form-based logins to deal with the case where
    // a resource is protected for some HTTP methods but not protected for
    // GET which is used after authentication when redirecting to the
    // protected resource.
    // TODO: This is similar to the FormAuthenticator.matchRequest() logic
    // Is there a way to remove the duplication?
    Session session = request.getSessionInternal(false);
    if (session != null) {
        SavedRequest savedRequest = (SavedRequest) session.getNote(Constants.FORM_REQUEST_NOTE);
        if (savedRequest != null &&
                decodedRequestURI.equals(savedRequest.getDecodedRequestURI())) {
            return true;
        }
    }

    return false;
}
 
Example 13
Source File: FormAuthenticator.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * 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(Request request) {

  // Has a session been created?
  Session session = request.getSessionInternal(false);
  if (session == null) {
    return (false);
}

  // Is there a saved request?
  SavedRequest sreq = (SavedRequest)
      session.getNote(Constants.FORM_REQUEST_NOTE);
  if (sreq == null) {
    return (false);
}

  // Is there a saved principal?
  if (session.getNote(Constants.FORM_PRINCIPAL_NOTE) == null) {
    return (false);
}

  // Does the request URI match?
  String decodedRequestURI = request.getDecodedRequestURI();
  if (decodedRequestURI == null) {
    return (false);
}
  return (decodedRequestURI.equals(sreq.getDecodedRequestURI()));
}
 
Example 14
Source File: AccessLogValve.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
public void addElement(StringBuilder buf, Date date, Request request,
        Response response, long time) {
    if (request == null) {
        buf.append('-');
    } else {
        Session session = request.getSessionInternal(false);
        if (session == null) {
            buf.append('-');
        } else {
            buf.append(session.getIdInternal());
        }
    }
}
 
Example 15
Source File: BaseOpenIDConnectAuthenticator.java    From tomcat-oidcauth with Apache License 2.0 5 votes vote down vote up
@Override
public void logout(final Request request) {

	final Session session = request.getSessionInternal(false);
	if (session != null) {
		session.removeNote(SESS_STATE_NOTE);
		session.removeNote(Constants.SESS_USERNAME_NOTE);
		session.removeNote(SESS_OIDC_AUTH_NOTE);
		session.removeNote(Constants.FORM_REQUEST_NOTE);
		session.getSession().removeAttribute(AUTHORIZATION_ATT);
	}

	super.logout(request);
}
 
Example 16
Source File: DatastoreValve.java    From tomcat-runtime with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * <p>If the manager contain a store, use it to persist the session at the end of the request.</p>
 */
@Override
public void invoke(Request request, Response response) throws IOException, ServletException {

  log.debug("Processing request with session:" + request.getRequestedSessionId());

  getNext().invoke(request, response);

  Context context = request.getContext();
  Manager manager = context.getManager();

  Session session = request.getSessionInternal(false);
  if (session != null && !isUriExcluded(request.getRequestURI())) {
    log.debug("Persisting session with id: " + session.getId());
    session.access();
    session.endAccess();

    if (manager instanceof StoreManager) {
      StoreManager storeManager = (StoreManager) manager;
      storeManager.getStore().save(session);
      storeManager.removeSuper(session);
    } else {
      log.error("In order to persist the session the manager must implement StoreManager");
    }
  } else {
    log.debug("Session not persisted (Non existent or the URI is ignored)");
  }

}
 
Example 17
Source File: MongoAccessLogValve.java    From tomcat-mongo-access-log with Apache License 2.0 5 votes vote down vote up
@Override
public void addElement(StringBuilder buf, DBObject result, Date date, Request request,
        Response response, long time) {
    if (request == null) {
        result.put("sessionId", '-');
    } else {
        Session session = request.getSessionInternal(false);
        if (session == null) {
            result.put("sessionId", '-');
        } else {
            result.put("sessionId", session.getIdInternal());
        }
    }
}
 
Example 18
Source File: FederationAuthenticator.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
protected boolean restoreRequest(Request request, HttpServletResponse response) throws IOException {

        Session session = request.getSessionInternal();
        LOG.debug("Restore request from session '{}'", session.getIdInternal());

        if (restoreRequest(request)) {
            LOG.debug("Proceed to restored request");
            return true;
        } else {
            LOG.warn("Restore of original request failed");
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return false;
        }
    }
 
Example 19
Source File: BaseOpenIDConnectAuthenticator.java    From tomcat-oidcauth with Apache License 2.0 4 votes vote down vote up
/**
 * If caching principal on the session by the authenticator is disabled,
 * check if the session has authentication information (username, password
 * or OP issuer ID) and if so, reauthenticate the user.
 *
 * @param request The request.
 * @param response The response.
 *
 * @return {@code true} if was successfully reauthenticated and no further
 * authentication action is required. If authentication logic should
 * proceed, returns {@code false}.
 */
protected boolean reauthenticateNoCache(final Request request,
		final HttpServletResponse response) {

	// get session
	final Session session = request.getSessionInternal(true);

	final boolean debug = this.log.isDebugEnabled();
	if (debug)
		this.log.debug("checking for reauthenticate in session "
				+ session.getIdInternal());

	// check if authentication info is in the session
	final String username =
		(String) session.getNote(Constants.SESS_USERNAME_NOTE);
	if (username == null)
		return false;

	// get the rest of the authentication info
	final Authorization authorization =
		(Authorization) session.getNote(SESS_OIDC_AUTH_NOTE);
	final String password =
		(String) session.getNote(Constants.SESS_PASSWORD_NOTE);

	// get the principal from the realm (try to reauthenticate)
	Principal principal = null;
	if (authorization != null) { // was authenticated using OpenID Connect
		if (debug)
			this.log.debug("reauthenticating username \""
					+ username + "\" authenticated by "
					+ authorization.getIssuer());
		principal = this.context.getRealm().authenticate(
				username);
	} else if (password != null) { // was form-based authentication
		if (debug)
			this.log.debug("reauthenticating username \""
					+ username + "\" using password");
		principal = this.context.getRealm().authenticate(
				username, password);
	}

	// check if could not reauthenticate
	if (principal == null) {
		if (debug)
			this.log.debug("reauthentication failed, proceed normally");
		return false;
	}

	// successfully reauthenticated, register the principal
	if (debug)
		this.log.debug("successfully reauthenticated username \""
				+ username + "\"");
	this.register(request, response, principal,
			HttpServletRequest.FORM_AUTH, username, password);

	// check if resubmit after successful authentication
	if (this.matchRequest(request)) {
		if (debug)
			this.log.debug("reauthenticated username \"" + username
					+ "\" for resubmit after successful authentication");
		return false;
	}

	// no further authentication action required
	return true;
}
 
Example 20
Source File: BaseOpenIDConnectAuthenticator.java    From tomcat-oidcauth with Apache License 2.0 4 votes vote down vote up
/**
 * Process regular unauthenticated request. Normally, saves the request in
 * the session and forwards to the configured login page.
 *
 * @param request The request.
 * @param response The response.
 *
 * @throws IOException If an I/O error happens communicating with the
 * client.
 */
protected void processUnauthenticated(final Request request,
		final HttpServletResponse response)
	throws IOException {

	// If this request was to the root of the context without a trailing
	// "/", need to redirect to add it else the submit of the login form
	// may not go to the correct web application
	if ((request.getServletPath().length() == 0)
			&& (request.getPathInfo() == null)) {
		final StringBuilder location = new StringBuilder(
				request.getDecodedRequestURI());
		location.append('/');
		if (request.getQueryString() != null)
			location.append('?').append(request.getQueryString());
		response.sendRedirect(
				response.encodeRedirectURL(location.toString()));
		return;
	}

	// get session
	final Session session = request.getSessionInternal(true);

	final boolean debug = this.log.isDebugEnabled();
	if (debug)
		this.log.debug("save request in session "
				+ session.getIdInternal());

	// save original request in the session before forwarding to the login
	try {
		this.saveRequest(request, session);
	} catch (final IOException e) {
		this.log.debug("could not save request during authentication", e);
		response.sendError(HttpServletResponse.SC_FORBIDDEN,
				sm.getString("authenticator.requestBodyTooBig"));
		return;
	}

	// forward to the login page
	this.forwardToLoginPage(request, response,
			this.context.getLoginConfig());
}