Java Code Examples for org.apache.catalina.Session#getNote()

The following examples show how to use org.apache.catalina.Session#getNote() . 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: FormAuthenticator.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Return the request URI (with the corresponding query string, if any)
 * from the saved request so that we can redirect to it.
 *
 * @param session Our current session
 */
protected String savedRequestURL(Session session) {

    SavedRequest saved =
        (SavedRequest) session.getNote(Constants.FORM_REQUEST_NOTE);
    if (saved == null) {
        return (null);
    }
    StringBuilder sb = new StringBuilder(saved.getRequestURI());
    if (saved.getQueryString() != null) {
        sb.append('?');
        sb.append(saved.getQueryString());
    }
    return (sb.toString());

}
 
Example 2
Source File: FormAuthenticator.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Return the request URI (with the corresponding query string, if any)
 * from the saved request so that we can redirect to it.
 *
 * @param session Our current session
 */
protected String savedRequestURL(Session session) {

    SavedRequest saved =
        (SavedRequest) session.getNote(Constants.FORM_REQUEST_NOTE);
    if (saved == null) {
        return (null);
    }
    StringBuilder sb = new StringBuilder(saved.getRequestURI());
    if (saved.getQueryString() != null) {
        sb.append('?');
        sb.append(saved.getQueryString());
    }
    return (sb.toString());

}
 
Example 3
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 4
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 5
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 6
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 7
Source File: FormAuthenticator.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Return the request URI (with the corresponding query string, if any)
 * from the saved request so that we can redirect to it.
 *
 * @param session Our current session
 * @return the original request URL
 */
protected String savedRequestURL(Session session) {
    SavedRequest saved =
        (SavedRequest) session.getNote(Constants.FORM_REQUEST_NOTE);
    if (saved == null) {
        return null;
    }
    StringBuilder sb = new StringBuilder(saved.getRequestURI());
    if (saved.getQueryString() != null) {
        sb.append('?');
        sb.append(saved.getQueryString());
    }
    return sb.toString();
}
 
Example 8
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 9
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 10
Source File: FederationAuthenticator.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
protected void resumeRequest(String contextId, HttpServletRequest request,
                             HttpServletResponse response) throws IOException {
    if (contextId == null) {
        LOG.warn("The context parameter has not been provided back with signin request.");
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    } else {
        Session session = ((Request)request).getSessionInternal();
        String originalURL = (String)session.getNote(FederationAuthenticator.SESSION_SAVED_URI_PREFIX + contextId);
        session.removeNote(FederationAuthenticator.SESSION_SAVED_URI_PREFIX + contextId); // Cleanup session

        try {
            if (originalURL != null) {
                LOG.debug("Restore request to {}", originalURL);
                response.sendRedirect(response.encodeRedirectURL(originalURL));
            } else {
                LOG.debug("User took so long to log on the session expired");
                if (landingPage == null) {
                    response.sendError(HttpServletResponse.SC_REQUEST_TIMEOUT, sm
                                       .getString("authenticator.sessionExpired"));
                } else {
                    // Redirect to landing page
                    String uri = request.getContextPath() + landingPage;
                    response.sendRedirect(response.encodeRedirectURL(uri));
                }
            }
        } catch (IOException e) {
            LOG.error("Cannot resume with request. {}", e.getMessage());
        }
    }
}
 
Example 11
Source File: FederationAuthenticator.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean matchRequest(Request request) {
    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) {
            synchronized (session) {
                session.setNote(Constants.FORM_REQUEST_NOTE, saved);
                return super.matchRequest(request);
            }
        }
    }
    return false;
}
 
Example 12
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 13
Source File: FormAuthenticator.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
/**
 * Restore the original request from information stored in our session.
 * If the original request is no longer present (because the session
 * timed out), return <code>false</code>; otherwise, return
 * <code>true</code>.
 *
 * @param request The request to be restored
 * @param session The session containing the saved information
 */
protected boolean restoreRequest(Request request, Session session)
        throws IOException {

    // Retrieve and remove the SavedRequest object from our session
    SavedRequest saved = (SavedRequest)
        session.getNote(Constants.FORM_REQUEST_NOTE);
    session.removeNote(Constants.FORM_REQUEST_NOTE);
    session.removeNote(Constants.FORM_PRINCIPAL_NOTE);
    if (saved == null) {
        return (false);
    }

    // Swallow any request body since we will be replacing it
    // Need to do this before headers are restored as AJP connector uses
    // content length header to determine how much data needs to be read for
    // request body
    byte[] buffer = new byte[4096];
    InputStream is = request.createInputStream();
    while (is.read(buffer) >= 0) {
        // Ignore request body
    }

    // Modify our current request to reflect the original one
    request.clearCookies();
    Iterator<Cookie> cookies = saved.getCookies();
    while (cookies.hasNext()) {
        request.addCookie(cookies.next());
    }

    String method = saved.getMethod();
    MimeHeaders rmh = request.getCoyoteRequest().getMimeHeaders();
    rmh.recycle();
    boolean cachable = "GET".equalsIgnoreCase(method) ||
                       "HEAD".equalsIgnoreCase(method);
    Iterator<String> names = saved.getHeaderNames();
    while (names.hasNext()) {
        String name = names.next();
        // The browser isn't expecting this conditional response now.
        // Assuming that it can quietly recover from an unexpected 412.
        // BZ 43687
        if(!("If-Modified-Since".equalsIgnoreCase(name) ||
             (cachable && "If-None-Match".equalsIgnoreCase(name)))) {
            Iterator<String> values = saved.getHeaderValues(name);
            while (values.hasNext()) {
                rmh.addValue(name).setString(values.next());
            }
        }
    }

    request.clearLocales();
    Iterator<Locale> locales = saved.getLocales();
    while (locales.hasNext()) {
        request.addLocale(locales.next());
    }

    request.getCoyoteRequest().getParameters().recycle();
    request.getCoyoteRequest().getParameters().setQueryStringEncoding(
            request.getConnector().getURIEncoding());

    ByteChunk body = saved.getBody();

    if (body != null) {
        request.getCoyoteRequest().action
            (ActionCode.REQ_SET_BODY_REPLAY, body);

        // Set content type
        MessageBytes contentType = MessageBytes.newInstance();

        // If no content type specified, use default for POST
        String savedContentType = saved.getContentType();
        if (savedContentType == null && "POST".equalsIgnoreCase(method)) {
            savedContentType = "application/x-www-form-urlencoded";
        }

        contentType.setString(savedContentType);
        request.getCoyoteRequest().setContentType(contentType);
    }

    request.getCoyoteRequest().method().setString(method);

    request.getCoyoteRequest().queryString().setString
        (saved.getQueryString());

    request.getCoyoteRequest().requestURI().setString
        (saved.getRequestURI());
    return (true);

}
 
Example 14
Source File: FormAuthenticator.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
/**
 * Restore the original request from information stored in our session.
 * If the original request is no longer present (because the session
 * timed out), return <code>false</code>; otherwise, return
 * <code>true</code>.
 *
 * @param request The request to be restored
 * @param session The session containing the saved information
 */
protected boolean restoreRequest(Request request, Session session)
        throws IOException {

    // Retrieve and remove the SavedRequest object from our session
    SavedRequest saved = (SavedRequest)
        session.getNote(Constants.FORM_REQUEST_NOTE);
    session.removeNote(Constants.FORM_REQUEST_NOTE);
    session.removeNote(Constants.FORM_PRINCIPAL_NOTE);
    if (saved == null) {
        return (false);
    }

    // Swallow any request body since we will be replacing it
    // Need to do this before headers are restored as AJP connector uses
    // content length header to determine how much data needs to be read for
    // request body
    byte[] buffer = new byte[4096];
    InputStream is = request.createInputStream();
    while (is.read(buffer) >= 0) {
        // Ignore request body
    }

    // Modify our current request to reflect the original one
    request.clearCookies();
    Iterator<Cookie> cookies = saved.getCookies();
    while (cookies.hasNext()) {
        request.addCookie(cookies.next());
    }

    String method = saved.getMethod();
    MimeHeaders rmh = request.getCoyoteRequest().getMimeHeaders();
    rmh.recycle();
    boolean cachable = "GET".equalsIgnoreCase(method) ||
                       "HEAD".equalsIgnoreCase(method);
    Iterator<String> names = saved.getHeaderNames();
    while (names.hasNext()) {
        String name = names.next();
        // The browser isn't expecting this conditional response now.
        // Assuming that it can quietly recover from an unexpected 412.
        // BZ 43687
        if(!("If-Modified-Since".equalsIgnoreCase(name) ||
             (cachable && "If-None-Match".equalsIgnoreCase(name)))) {
            Iterator<String> values = saved.getHeaderValues(name);
            while (values.hasNext()) {
                rmh.addValue(name).setString(values.next());
            }
        }
    }

    request.clearLocales();
    Iterator<Locale> locales = saved.getLocales();
    while (locales.hasNext()) {
        request.addLocale(locales.next());
    }

    request.getCoyoteRequest().getParameters().recycle();
    request.getCoyoteRequest().getParameters().setQueryStringEncoding(
            request.getConnector().getURIEncoding());

    ByteChunk body = saved.getBody();

    if (body != null) {
        request.getCoyoteRequest().action
            (ActionCode.REQ_SET_BODY_REPLAY, body);

        // Set content type
        MessageBytes contentType = MessageBytes.newInstance();

        // If no content type specified, use default for POST
        String savedContentType = saved.getContentType();
        if (savedContentType == null && "POST".equalsIgnoreCase(method)) {
            savedContentType = "application/x-www-form-urlencoded";
        }

        contentType.setString(savedContentType);
        request.getCoyoteRequest().setContentType(contentType);
    }

    request.getCoyoteRequest().method().setString(method);

    request.getCoyoteRequest().queryString().setString
        (saved.getQueryString());

    request.getCoyoteRequest().requestURI().setString
        (saved.getRequestURI());
    return (true);

}
 
Example 15
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;
}