This spring Steve Wasleski (Jazz Jumpstart team), Steve Speicher (OSLC and Change Management Architect) and myself built a workshop on Jazz Extensibility for Innovate 2010, the Rational Software Conference. This workshop, labs and source code, has been published on jazz.net under this link: OSLC Workshop and Jazz Extensions Workshop.
During the labs elaboration, I had to understand how the Jazz Team Server manages the authentication: Form-based Authentication and how to interact with it as a client. Because it took me some times to figure it out, I think this blog is a good place to extract this part of the lab and share it with the “Rest of the World”.
The Form-Based Authentication is a three steps process:
- The client requests a protected resource.
- If the client is not authenticated, the server redirects to the login page, and the client has to fill the form and submit it to the server.
- If the login has succeeded, the client submits a request the protected resource again and should get it back.
Clearly, the behavior doesn’t seem obvious because the process seems to indicate that it requires a human behind interaction.
Actually, you can perfectly emulate and manage this interaction programmatically.
Let say you want to reach a resource designated by a URL (protectedResource) which is protected by a Form-based authentication.
The following snippet code describes how you will implement this 3-steps process:
HttpGet documentGet = new HttpGet(protectedResource);
documentGet.addHeader("accept", mediaType);
//
// Step (1): Request the protected resource
//
HttpResponse response = httpClient.execute(documentGet);
if (response.getStatusLine().getStatusCode() == 200) {
Header header =
response.getFirstHeader("x-com-ibm-team-repository-web-auth-msg");
if ((header!=null) && ("authrequired".equals(header.getValue()))) {
response.getEntity().consumeContent();
// The server requires an authentication: Create the login form
HttpPost formPost = new HttpPost(serverURI+"/j_security_check");
List nvps = new ArrayList();
nvps.add(new BasicNameValuePair("j_username", login));
nvps.add(new BasicNameValuePair("j_password", password));
formPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
//
// Step (2): The client submits the login form
//
HttpResponse formResponse = httpClient.execute(formPost);
header = formResponse.getFirstHeader("X-com-ibm-team-repository-web-auth-msg");
if ((header!=null) && ("authfailed".equals(header.getValue()))) {
// The login failed
throw new InvalidCredentialsException("Authentication failed");
} else {
// The login succeed
formResponse.getEntity().consumeContent();
//
// Step (3): Request again the protected resource
//
HttpGet documentGet2 = new HttpGet(protectedResource);
documentGet2.addHeader("accept", mediaType);
return httpClient.execute(documentGet2);
}
}
return response;
This code is based on Apache HTTP Client (Release 4.0.1) APIs.
I hope it will help.
-Philippe
43.400223
1.560553