Skip to content

Instantly share code, notes, and snippets.

@abeluck
Created March 7, 2024 10:08
Show Gist options
  • Save abeluck/2cde182eecced0f1a61ee77085124a22 to your computer and use it in GitHub Desktop.
Save abeluck/2cde182eecced0f1a61ee77085124a22 to your computer and use it in GitHub Desktop.
How to modify Jetty Client Request after TLS handshake is complete?
// Jetty version: 12.0.6
public class JettyClient {
public static void main(String[] args) throws Exception {
SecurityProviders.init(); // initializes the Conscrypt and BouncyCastle security providers
SslContextFactory.Client sslContextFactory = new SslContextFactory.Client();
// This disables SSL certificate validation
// handy for localhost testing, not so handy in production
sslContextFactory.setTrustAll(true);
SigAuthClientListener sigAuthClientListener = new SigAuthClientListener();
ClientConnector clientConnector = new ClientConnector();
clientConnector.setSslContextFactory(sslContextFactory);
// clientConnector.setConnectBlocking(true); // this doesn't change anything
HttpClient client = new HttpClient(new HttpClientTransportDynamic(clientConnector));
client.addBean(sigAuthClientListener);
client.start();
String host = "127.0.0.1";
int port = 8090;
String url = String.format("https://%s:%d/ping", host, port);
Request request = client.newRequest(url).listener(sigAuthClientListener);
ContentResponse res = request.send();
System.out.println("Got response: " + res.getStatus() + " " + res.getReason());
System.out.println(res.getContentAsString());
client.stop();
}
}
// Jetty version: 12.0.6
public class SigAuthClientListener implements Connection.Listener, Request.Listener, SslHandshakeListener {
@Override
public void onOpened(Connection connection) {
System.out.println("Connection opened");
}
@Override
public void onBegin(Request request) {
System.out.println("Request begin");
// This is my last chance to modify the request headers,
// but the TLS handshake hasn't completed yet!
}
@Override
public void handshakeSucceeded(Event event) throws SSLException {
System.out.println("Handshake succeeded");
}
@Override
public void onCommit(Request request) {
System.out.println("Request commit");
// This happens after the handshake
// but we cannot modify the headers here, they have already been serialized
// :(
}
}
/*
Output:
Connection opened
Request begin
Handshake succeeded
Request commit
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment