Grizzly: Illegal attempt to exceed the configured maximum number of headers - jersey-2.0

I am using Grizzly/Jersey/Jackson in a RESTful web service server application. For certain interactions, a large number of HTTP headers may be returned in a response. By default, Grizzy sets a maxium number of response headers to 100.
Reading the Grizzy Http Server Framework Overview, it seems like the maxResponseHeaders (maximum number of headers a response may send to a client) can somehow be configured, but it's not clear how that is done when Grizzly is stacked up with Jersey.
Any suggestions on what to try to set this configuration?
This is how I am currently configuring Grizzly and Jackson:
packages(true, Config.CONFIG_RESOURCE_BASE_PACKAGE);
register(JacksonFeature.class);
register(GrizzlyHttpContainerProvider.class);
register(CustomInjectables.class);
register(RolesAllowedDynamicFeature.class);
register(AccessSecurityFilter.class);
String host = Config.get("webserver.address");
int port = Config.getInteger("webserver.port");
boolean secure = Config.getBoolean("webserver.secure");
if (secure) {
SSLContextConfigurator sslContextConfigurator = new SSLContextConfigurator();
sslContextConfigurator.setKeyStoreFile(Config
.get("webserver.keystore.location"));
sslContextConfigurator.setKeyStorePass(Config
.get("webserver.keystore.password"));
boolean clientMode = false;
boolean needClientAuth = false;
boolean wantClientAuth = false;
SSLEngineConfigurator sslEngineConfigurator = new SSLEngineConfigurator(
sslContextConfigurator, clientMode, needClientAuth,
wantClientAuth);
URI uri = URI.create("https://" + host + ":" + port);
log.info("Starting web server (secure): " + uri + " ...");
server = GrizzlyHttpServerFactory.createHttpServer(uri, this, true,
sslEngineConfigurator, true);
} else {
URI uri = URI.create("http://" + host + ":" + port);
log.info("Starting web server: " + uri + " ...");
server = GrizzlyHttpServerFactory.createHttpServer(uri, this, true);
}
This is the stack when I exceed the maximum number of response headers:
Apr 24, 2017 10:28:46 PM org.glassfish.grizzly.filterchain.DefaultFilterChain execute
WARNING: GRIZZLY0013: Exception during FilterChain execution
org.glassfish.grizzly.http.util.MimeHeaders$MaxHeaderCountExceededException: Illegal attempt to exceed the configured maximum number of headers: 100
at org.glassfish.grizzly.http.util.MimeHeaders.createHeader(MimeHeaders.java:396)
at org.glassfish.grizzly.http.util.MimeHeaders.setValue(MimeHeaders.java:498)
at org.glassfish.grizzly.http.HttpServerFilter.prepareResponse(HttpServerFilter.java:944)
at org.glassfish.grizzly.http.HttpServerFilter.encodeHttpPacket(HttpServerFilter.java:834)
at org.glassfish.grizzly.http.HttpCodecFilter.handleWrite(HttpCodecFilter.java:1407)
at org.glassfish.grizzly.filterchain.ExecutorResolver$8.execute(ExecutorResolver.java:111)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.filterchain.FilterChainContext.write(FilterChainContext.java:890)
at org.glassfish.grizzly.filterchain.FilterChainContext.write(FilterChainContext.java:858)
at org.glassfish.grizzly.http.io.OutputBuffer.flushBuffer(OutputBuffer.java:1029)
at org.glassfish.grizzly.http.io.OutputBuffer.flushBinaryBuffers(OutputBuffer.java:1016)
at org.glassfish.grizzly.http.io.OutputBuffer.flushAllBuffers(OutputBuffer.java:987)
at org.glassfish.grizzly.http.io.OutputBuffer.close(OutputBuffer.java:716)
at org.glassfish.grizzly.http.server.NIOWriterImpl.close(NIOWriterImpl.java:111)
at org.glassfish.grizzly.http.server.util.HtmlHelper.sendErrorPage(HtmlHelper.java:103)
at org.glassfish.grizzly.http.server.Response.sendError(Response.java:1358)
at org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpContainer$ResponseWriter.failure(GrizzlyHttpContainer.java:287)
at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:486)
at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:316)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:291)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1140)
at org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpContainer.service(GrizzlyHttpContainer.java:375)
at org.glassfish.grizzly.http.server.HttpHandler$1.run(HttpHandler.java:224)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Unknown Source)

The firs thing you need to do is have the server not automatically start when you call createHttpServer. Currently, you are passing true as the last argument, which is saying that is should auto-start. This configuration is already the default. So it's mainly used to set the value to false, meaning don't auto-start. So set that value to false.
Now that the server is not auto-starting, we can configure it. The specific configuration of the setMaxResponseHeader is a configuration on the NetworkListener. You can get that from the HttpServer.
final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(...);
final NetworkListener listener = server.getListener("grizzly");
listener.setMaxResponseHeaders(300);
server.start();
Now we manually start the server after configuration. The one thing I'm not sure about if there is a better way to get the listener. I just hard coded the "grizzly" because what I did prior was just iterate through server.getListeners() and print out all the names, and saw that "grizzly" was the only one available. So that's what I used to test.
Aside from the NetworkListener configuration, there are also other server related configurations you can make through the ServerConfiguration. You can get the with server.getServerConfiguration()

Related

How to return error response to calling channel when TCP destination gives 'Connection refused'

I have this pattern:
channel ESANTE_MPI_CREATE_PATIENT_LISTENER (with a MLLP listener) calls channel ESANTE_MPI_CREATE_PATIENT that calls a TCP destination.
If connection cannot be done in the TCP destination inside ESANTE_MPI_CREATE_PATIENT then this channel reports an error for this destination:(ERROR: ConnectException: Connection refused (Connection refused))
The response transformer does not seem to be called (which is normal as there is no response).
I wonder how I can report the error back to the calling channel ESANTE_MPI_CREATE_PATIENT_LISTENER ?
PS: When tcp destination responds, then I use the response transformer to parse the received frame and create a response message (json error/ok) for the calling channel. Everything works fine here.
My question ends up with: How to trap a Connection refused in a TCP destination to create a response message.
I finally managed this by using the postprocessor script in ESANTE_MPI_CREATE_PATIENT to get the response of the connector and then force a message.
// fake error message prepared for connection refused.
// we put this as the response of the channel destination in order to force a understandable error message.
const sErrorMsg = {
status: "error",
error: "connection refused to eSanté MPI"
};
const TCP_CONNECTOR_ESANTE_MPI_RANK = 2; // WARNING: be sure to take the correct connector ID as displayed into destination.
const TCP_CONNECTOR_ESANTE_MPI_DNAME = 'd' + TCP_CONNECTOR_ESANTE_MPI_RANK; // WARNING: be sure to take the correct connector ID as displayed into destination.
/*
var cms = message.getConnectorMessages(); // returns message but as Immutable
responses. not what we want: we use responseMap instead.
var key = TCP_CONNECTOR_ESANTE_MPI_RANK;
logger.debug(" Response Data=" + cms.get(key).getResponseData());
logger.debug(" Response Data0=" + cms.get(key).getResponseError());
logger.debug(" Response Data1=" + cms.get(key).getResponseData().getError());
logger.debug(" Response Data2=" + cms.get(key).getResponseData().getMessage());
logger.debug(" Response Data3=" + cms.get(key).getResponseData().getStatusMessage());
logger.debug(" Response Data4=" + cms.get(key).getResponseData().getStatus());
*/
var responseMPI = responseMap.get(TCP_CONNECTOR_ESANTE_MPI_DNAME); // return a mutable reponse :-)
if (responseMPI.getStatus()=='ERROR' &&
responseMPI.getStatusMessage().startsWith('ConnectException: Connection refused')) {
// build a error message for this dedicated case
logger.error("connection refused detected");
responseMPI.setMessage(JSON.stringify(sErrorMsg)); // force the message to be responsed.
}
return;

javax.security.sasl.SaslException: Authentication failed: the server presented no authentication mechanisms in Wildfly 10.1

I am new to EJBs, and I am trying to perform remote invocations on stateless and stateful beans that I have deployed on a pod in my project that is based on Wildfly 10.1 in the new OpenShift 3 (Origin). The code that I am using for initializing the client context looks like:
Properties clientProperties = new Properties();
clientProperties.put("remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED", "false");
clientProperties.put("remote.connections", "default");
clientProperties.put("remote.connection.default.host", "localhost");
clientProperties.put("remote.connection.default.port", "8080");
clientProperties.put("remote.connection.default.username", "****");
clientProperties.put("remote.connection.default.password", "****"); clientProperties.put("remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS", "false");
clientProperties.put("remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT", "false");
EJBClientContext.setSelector(new ConfigBasedEJBClientContextSelector(new
PropertiesBasedEJBClientConfiguration(clientProperties)));
Properties contextProperties = new Properties();
contextProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
contextProperties.put(Context.SECURITY_PRINCIPAL, "****"); //username
contextProperties.put(Context.SECURITY_CREDENTIALS, "****"); //password
Context context = new InitialContext(contextProperties);
String appName = "CloudEAR";
String moduleName = "CloudEjb";
String distinctName = "";
String beanName = "Calculator";
String qualifiedRemoteView = "cloudEJB.view.CalculatorRemote";
String lookupString = "ejb:" + appName + "/" + moduleName + "/" + distinctName + "/" + beanName + "!" + qualifiedRemoteView;
Calculator calculator = (CalculatorRemote) context.lookup(lookupString);
int sum = calculator.sum(10, 10);
And the error message that I get is:
WARN: Could not register a EJB receiver for connection to localhost:8080
javax.security.sasl.SaslException: Authentication failed: the server presented no authentication mechanisms
at org.jboss.remoting3.remote.ClientConnectionOpenListener$Capabilities.handleEvent(ClientConnectionOpenListener.java:378)
at org.jboss.remoting3.remote.ClientConnectionOpenListener$Capabilities.handleEvent(ClientConnectionOpenListener.java:240)
at org.xnio.ChannelListeners.invokeChannelListener(ChannelListeners.java:92)
at org.xnio.channels.TranslatingSuspendableChannel.handleReadable(TranslatingSuspendableChannel.java:198)
at org.xnio.channels.TranslatingSuspendableChannel$1.handleEvent(TranslatingSuspendableChannel.java:112)
at org.xnio.ChannelListeners.invokeChannelListener(ChannelListeners.java:92)
at org.xnio.ChannelListeners$DelegatingChannelListener.handleEvent(ChannelListeners.java:1092)
at org.xnio.ChannelListeners.invokeChannelListener(ChannelListeners.java:92)
at org.xnio.conduits.ReadReadyHandler$ChannelListenerHandler.readReady(ReadReadyHandler.java:66)
at org.xnio.nio.NioSocketConduit.handleReady(NioSocketConduit.java:89)
at org.xnio.nio.WorkerThread.run(WorkerThread.java:567)
at ...asynchronous invocation...(Unknown Source)
at org.jboss.remoting3.EndpointImpl.doConnect(EndpointImpl.java:272)
at org.jboss.remoting3.EndpointImpl.connect(EndpointImpl.java:388)
Initially I tried using the "jboss-ejb-client.properties" file, but that wasn't even able to make the remote connection. Now I am manually creating and configuring the EJBClientContext, and at least is successfully connecting to the remote server, but the invocation filas because of authentication failures.
I remember that we used to solve this issue by removing the "security realm" argument in "standalone.xml" files in older versions of OpenShift; however I am not able to find that file in the new version anymore. I have been looking at concepts such as secrets, volumes etc. but I really don't have a clear understanding how this works. When I create a new secret and try to associate it with my pod, the new deployment procedure fails. I would really appreciate any help.

POST request on arduino with ESP8266 using WifiESP library

I am attempting to make RESTful POST request using the WifiESP library (https://github.com/bportaluri/WiFiEsp). I'm able to successfully make the request with curl, but consistently get an error using the Arduino and ESP. I suspect the problem is related to the manual formatting of the POST request the library requires, but I don't see anything wrong. Here my sanitized code:
if (client.connect(server, 80)) {
Serial.println("Connected to server");
// Make a HTTP request
String content = "{'JSON_key': 2.5}"; // some arbitrary JSON
client.println("POST /some/uri HTTP/1.1");
client.println("Host: http://things.ubidots.com");
client.println("Accept: */*");
client.println("Content-Length: " + sizeof(content));
client.println("Content-Type: application/json");
client.println();
client.println(content);
}
The error I get (via serial monitor) is this:
Connected to server
[WiFiEsp] Data packet send error (2)
[WiFiEsp] Failed to write to socket 3
[WiFiEsp] Disconnecting 3
My successful curl requests looks like this:
curl -X POST -H "Content-Type: application/json" -d 'Some JSON' http://things.ubidots.com/some/uri
After some experimentation, here is the solution to the multiple problems.
The JSON object was not correctly formatted. Single quotes were not accepted, so I needed to escape the double quotes.
The host does not need "http://" in a POST request; POST is a HTTP method.
The sizeof() method returns the size, in bytes, of the variable in memory rather than the length of the string. It needs to be replaced by .length().
Appending an integer to a string requires a cast.
This is the corrected code:
if (client.connect(server, 80)) {
Serial.println("Connected to server");
// Make the HTTP request
int value = 2.5; // an arbitrary value for testing
String content = "{\"JSON_key\": " + String(value) + "}";
client.println("POST /some/uri HTTP/1.1");
client.println("Host: things.ubidots.com");
client.println("Accept: */*");
client.println("Content-Length: " + String(content.length()));
client.println("Content-Type: application/json");
client.println();
client.println(content);
}
The code explained by Troy D is right and it's working .I think the error in posting the data to the server is due to this line
client.println("Content-Length: " + sizeof(content));
and the correct way is
client.println("Content-Length: " + String(content.length()));
Now coming to this error
Connected to server
[WiFiEsp] Data packet send error (2)
[WiFiEsp] Failed to write to socket 3
[WiFiEsp] Disconnecting 3
This is the error of library you can ignore it.
The problem with "Data packet send error (2)", "Failed to write to socket 3" and "Disconnecting 3" is not a problem within the WifiEsp library as far as I can see, believe it's more likely to be within the AT firmware. By default the http headers contain a "Connection: close" parameter which in normal cases should be correct. However with this bug the server will get disconnected before the reply is received on the client side and any response from the server will be identified as garbage data. Using the value "Connection: keep-alive" as a workaround will make it possible to receive the acceptance from the server in a proper way.
I'm running my Arduino + ESP8266-07 against a MVC based Web Api that I created on one of my servers and in the controllers Post-method I use a single string as return value, the value I return if everything is ok is simply one of the strings that WifiEsp keeps track of (It will still include the http status code in the response header that it returns)
public async Task<string> Post([FromBody]JObject payload)
{
//Code to handle the data received, in my case I log unit ip, macaddress, datetime and sensordata into a db with entity framework
return "SEND OK";
}
So in your Arduino code try following instead:
String PostHeader = "POST http://" + server + ":" + String(port) + "/api/values HTTP/1.1\r\n";
PostHeader += "Connection: keep-alive\r\n";
PostHeader += "Content-Type: application/json; charset=utf-8\r\n";
PostHeader += "Host: " + server + ":" + String(port) + "\r\n";
PostHeader += "Content-Length: " + String(jsonString.length()) + "\r\n\r\n";
PostHeader += jsonString;
client.connect(server.c_str(), port);
client.println(PostHeader);
client.stop();
In the file debug.h located in the library source code you could alter a define and get more output to your serial console. Open the file and change
#define _ESPLOGLEVEL_ 3
to
#define _ESPLOGLEVEL_ 4
Save the file and recompile/deploy your source code to your Arduino and you will get extensive information about all AT commands the library sends and what the library receives in return.

Spring cloud eureka client to multiple eureka servers

I am able to get the eureka server to operate in a peer to peer mode. But one thing I am curious about is how do I get a service discovery client to register to multiple eureka servers.
My use case is this:
Say I have a service registering to one of the eureka servers (e.g. server A) and that registration is replicated to its peer. The service is actually pointing at server A. If server A goes down, and the client expects to renew with server A, how do the renewal work if server A is no longer present.
Do I need to register with both and if not then how does the renewal happen if the client cannot communicate with server A. Does it have some knowledge of server B (from its initial and/or subsequent comms with A) and fail over to do its registration renewal there? That is not clear in any of the docs and I need to verify
So based on the answer, I added the following to my application.yml
eureka:
# these are settings for the client that gets services
client:
# enable these two settings if you want discovery to work
registerWithEureka: true
fetchRegistry: true
serviceUrl:
defaultZone: http://localhost:8762/eureka/, http://localhost:8761/eureka/
It only registers to the first in the comma separated list. If I switch them around the registration flips between eureka servers.
I can see that it does separate these based on comma but my guess is that Eureka does not use this underneath (from EurekaClientConfigBean.java)
#Override
public List<String> getEurekaServerServiceUrls(String myZone) {
String serviceUrls = this.serviceUrl.get(myZone);
if (serviceUrls == null || serviceUrls.isEmpty()) {
serviceUrls = this.serviceUrl.get(DEFAULT_ZONE);
}
if (serviceUrls != null) {
return Arrays.asList(serviceUrls.split(","));
}
return new ArrayList<>();
}
I just reviewed the source code for Eureka 1.1.147. It works differently that i expected but at least I know now.
You can put multiple service urls in the set
serviceUrl:
defaultZone: http://localhost:8762/eureka/, http://localhost:8761/eureka/
But the register action only uses the first one to register. There remaining are used only if attempting to contact the first fails.
from (DiscoveryClient.java)
/**
* Register with the eureka service by making the appropriate REST call.
*/
void register() {
logger.info(PREFIX + appPathIdentifier + ": registering service...");
ClientResponse response = null;
try {
response = makeRemoteCall(Action.Register);
isRegisteredWithDiscovery = true;
logger.info(PREFIX + appPathIdentifier + " - registration status: "
+ (response != null ? response.getStatus() : "not sent"));
} catch (Throwable e) {
logger.error(PREFIX + appPathIdentifier + " - registration failed"
+ e.getMessage(), e);
} finally {
if (response != null) {
response.close();
}
}
}
which calls
private ClientResponse makeRemoteCall(Action action) throws Throwable {
return makeRemoteCall(action, 0);
}
It only calls the backup when an exception is thrown in the above makeRemoteCall(action, 0) call
} catch (Throwable t) {
closeResponse(response);
String msg = "Can't get a response from " + serviceUrl + urlPath;
if (eurekaServiceUrls.get().size() > (++serviceUrlIndex)) {
logger.warn(msg, t);
logger.warn("Trying backup: " + eurekaServiceUrls.get().get(serviceUrlIndex));
SERVER_RETRY_COUNTER.increment();
return makeRemoteCall(action, serviceUrlIndex);
} else {
ALL_SERVER_FAILURE_COUNT.increment();
logger.error(
msg
+ "\nCan't contact any eureka nodes - possibly a security group issue?",
t);
throw t;
}
So you can't really register to two eureka servers simultaneously from this code. Unless I missed something.
Your client application should be provided a list of Eureka URLs. The URLs are comma separated.
Yes, as per the documentation, the flow is:
client registers to the first available eureka server
registrant information is replicated between eureka server nodes.
So multiple registration is not only not needed but should be avioded.
Please add below property in application.property or application.yml file
eureka.client.service-url.defaultZone = http://localhost:8761/eureka,http://localhost:8762/eureka
Services will be registered with both eureka server.If one eureka server is down then request will be served from other eureka server.
If you want to a workaround to register on multiple eureka servers.
please review my answer on similar question: https://stackoverflow.com/a/60714917/7982168

Apache Wink Client - Test a REST service using form auth

I am trying to use the Wink RestClient to do functional testing on a Rest service endpoint. I use mocks for unit testing but I'd like to functionally test it as an endpoint consumer.
I understand some will object to me calling it a REST endpoint while using form-based auth but that is the current architecture I have.
The majority of the resources I want to test are protected resources and the application (running on Tomcat6) is protected by form authentication. (as in the below web.xml snippet).
What I've tried so far is to make an initial call to an unprotected resource, to obtain the set-cookie header, that contains JSESSIONID, and use that JSESSIONID in the header ( via Resource.cookie() ) in subsequent requests but that does not yield fruit.
web.xml
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/login.html</form-login-page>
<form-error-page>/login.html?failure=true</form-error-page>
</form-login-config>
</login-config>
My Wink RestClient code looks like below. All responses are 200, but two things I notice are that the response from the call to /j_security_check/ does not include the jsessionid cookie, and the call to the protected resource said I had a signin failure. The payload for the call to j_security_check was captured directly from a previous successful browser request intercepted.
ClientConfig config = new ClientConfig();
config.setBypassHostnameVerification(true);
RestClient restClient = new RestClient(config);
Resource unprotectedResource = restClient.resource( BASE_URL + "/");
unprotectedResource.header( "Accept", "*/*" );
ClientResponse clientResponse = unprotectedResource.get();
String response = clientResponse.getEntity(String.class);
// get jSession ID
String jSessionId = clientResponse.getHeaders().get("set-cookie").get(0);
jSessionId = jSessionId.split(";")[0];
System.out.println(jSessionId);
// create a request to login via j_security_check
Resource loginResource = restClient.resource(BASE_URL + "/j_security_check/");
loginResource.accept("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
loginResource.header("referer", "http://localhost:8080/contextroot/");
loginResource.cookie( jSessionId );
loginResource.header("Connection", "keep-alive");
loginResource.header("Content-Type", "application/x-www-form-urlencoded");
loginResource.header("Content-Length", "41");
ClientResponse loginResponse = loginResource.post("j_username=*****&j_password=*************");
/* the loginResponse, as this point, does not have the jsessionid cookie, my browser client does */
Resource protectedResource = restClient.resource(BASE_URL + "/protected/test/");
systemResource.accept("application/json");
systemResource.cookie( jSessionId );
ClientResponse systemResponse = systemResource.get();
response = clientResponse.getEntity(String.class);
System.out.println(response);
Any thoughts or experience with using the Wink RestClient to exercise form-auth-protected resources would be greatly appreciated. I suppose I'd entertain other frameworks, I have heard of REST-Assured and others, but since the application uses Wink and the RestClient seems to provide me with what I need, I figured I'd stick with it.
Found the problem, and the solution
j_security_check was responding to my POST request (to authenticate), with a #302/redirect. That was being followed by the wink RestClient, but my JSESSIONID cookie was not being appended to it. That was causing the response (from the redirected URL) to contain a set-cookie header, with a new header. My subsequent calls, into which I inserted the JSESSIONID from the first call, failed, because that cookie was expired. All I needed to do was instruct the RestClient to NOT follow redirects. If the redirect were necessary, I would construct it on my own, containing the appropriate cookie.
Chromium and Firefox carry the cookie from the original request to the redirected request so it's all good.
Here is some code that worked for me, using JUnit4, RestClient from the Apache Wink project (and a Jackson ObjectMapper)
#Test
public void testGenerateZipEntryName() throws JsonGenerationException, JsonMappingException, IOException
{
final ObjectMapper mapper = new ObjectMapper();
final String BASE_URL = "http://localhost:8080/rest";
// Configure the Rest client
ClientConfig config = new ClientConfig();
config.proxyHost("localhost"); // helpful when sniffing traffic
config.proxyPort(50080); // helpful when sniffing traffic
config.followRedirects(false); // This is KEY for form auth
RestClient restClient = new RestClient(config);
// Get an unprotected resource -- to get a JSESSIONID
Resource resource = restClient.resource( BASE_URL + "/");
resource.header( "Accept", "*/*" );
ClientResponse response = resource.get();
// extract the jSession ID, in a brittle and ugly way
String jSessId = response.getHeaders().get("set-cookie").get(0).split(";")[0].split("=")[1];
// Get the login resource *j_security_check*
resource = restClient.resource(BASE_URL + "/j_security_check");
resource.cookie("j_username_tmp=admin; j_password_tmp=; JSESSIONID=" + jSessId);
resource.header("Content-Type", "application/x-www-form-urlencoded");
resource.header("Content-Length", "41");
// Verify that login resource redirects us
response = resource.post("j_username=admin&j_password=***********");
assertTrue( response.getStatusCode() == 302 );
// Grab a public resource
resource = restClient.resource(BASE_URL + "/");
resource.cookie("j_username_tmp=admin; j_password_tmp=; JSESSIONID=" + jSessId);
response = resource.get();
// verify status of response
assertTrue( response.getStatusCode() == 200 );
// Grab a protected resource
resource = restClient.resource(BASE_URL + "/rest/system");
resource.cookie("j_username_tmp=admin; j_password_tmp=; JSESSIONID=" + jSessId);
// Verify resource returned OK
response = resource.contentType("application/json").accept("*/*").get();
assertTrue( response.getStatusCode() == 200 );
// Deserialize body of protected response into domain object for further testing
MyObj myObj = mapper.readValue(response.getEntity(String.class), MyObj.class );
assertTrue( myObj.customerArchived() == false );
}