Skip to content

Instantly share code, notes, and snippets.

@pglezen
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pglezen/5379342d41b558100e94 to your computer and use it in GitHub Desktop.
Save pglezen/5379342d41b558100e94 to your computer and use it in GitHub Desktop.
Use Jersey to authenticate with WebSphere Application Server LTPA cookies.
package org.acme.cc.client.http;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
public class Main {
public static void main(String[] args) {
HttpAuthenticationFeature basicAuth = HttpAuthenticationFeature.basic("paul", "paul");
Client client = ClientBuilder.newClient();
// client.register(basicAuth); // This causes all invocations to use basicAuth.
WebTarget target = client.target("http://localhost:9804/consumer");
WebTarget credTarget = target.path("creds/json");
credTarget.register(basicAuth);
NewCookie ltpaCookie = callAuth(credTarget);
System.out.println("Waiting 6 minutes for LTPA token to expire ...");
try {
Thread.sleep(360000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println("Done waiting.");
WebTarget ccTarget = target.path("cc/json");
Invocation.Builder ccBuilder = ccTarget.request(MediaType.APPLICATION_JSON_TYPE);
LinkedHashMap<String, String> ccJsonRequest = new LinkedHashMap<String, String>();
ccJsonRequest.put("CCNo", "g4926032");
ccJsonRequest.put("LastName", "Smith");
try {
ObjectMapper jacksonMapper = new ObjectMapper();
for (short retriesLeft = 2; retriesLeft > 0; retriesLeft--) {
if (ltpaCookie != null) {
ccBuilder.cookie(ltpaCookie);
System.out.println("Added LTPA cookie to CC request builder.");
}
Invocation ccInvocation = ccBuilder.buildPost(Entity.entity(jacksonMapper.writeValueAsString(ccJsonRequest), MediaType.APPLICATION_JSON_TYPE));
Response ccResponse = ccInvocation.invoke();
int status = ccResponse.getStatus();
System.out.println(" CC Response status = " + status);
if (status == 200) {
retriesLeft = 0;
System.out.println("CC Response " + (ccResponse.hasEntity() ? "has an" : "does not have an") + " entity.");
String responseString = ccResponse.readEntity(String.class);
System.out.println("CC Response string = " + responseString);
} else if (status == 401) {
System.out.println("LTPA cookie failed ... re-authenticating.");
ltpaCookie = callAuth(credTarget);
}
}
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// Call the auth target and return the LTPA cookie that results if
// the authentication was successful. Return null otherwise.
//
static NewCookie callAuth(WebTarget target) {
NewCookie result = null;
Invocation.Builder credInvocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE);
Response credResponse = credInvocationBuilder.get();
System.out.println("Credential Response status = " + credResponse.getStatus());
System.out.println("Credential Response " + (credResponse.hasEntity() ? "has an" : "does not have an") + " entity.");
Map<String, NewCookie> cookies = credResponse.getCookies();
result = cookies.get("LtpaToken2");
for (String cookieName : cookies.keySet()) {
NewCookie c = cookies.get(cookieName);
System.out.println("Cookie key: " + cookieName);
System.out.println("\t name: " + c.getName());
System.out.println("\t value: " + c.getValue());
System.out.println("\t domain: " + c.getDomain());
System.out.println("\t path: " + c.getPath());
System.out.println("\t expiry: " + c.getExpiry());
System.out.println("\tmax age: " + c.getMaxAge());
}
String responseString = credResponse.readEntity(String.class);
System.out.println("Response string = " + responseString);
ObjectMapper jacksonMapper = new ObjectMapper();
try {
Map<String, Object> jsonResponse = jacksonMapper.readValue(responseString, new TypeReference<Map<String, Object>>() {});
System.out.println("Response:");
System.out.println("\tSecurity name: " + jsonResponse.get("SecurityName"));
System.out.println("\tUnique ID: " + jsonResponse.get("UniqueID"));
ArrayList<String> groups = (ArrayList<String>)jsonResponse.get("Groups");
if (groups.size() > 0) {
System.out.println("\tGroups:");
for (String g : groups) {
System.out.println("\t\tGroup name: " + g);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
Credential Response status = 200
Credential Response has an entity.
Cookie key: LtpaToken2
name: LtpaToken2
value: 82Tgj6s0RcAeHm3ZmZToMsyHqcylBXpKSxjUSc+rZ4WRHgV7khW2ySkNGQZbKP0xspH++cLJTonPjz9hXiiI1J7iU8DZTQSNkzIqQUmiB6PHD3khO14NO51Hh11QLxpouE1+WN5Wwsqijs8BlC0yHCg/xKxL1GL7VSmDHwAMnBiMulG2BHAFjQC7hBdp3PY3GBi4AEdfP2Py7Dci8+To+CLH9QMD1T+DSqxu751vUYEILng0BMuvqFwJHevSop0yHSuAnQ7z8NR5sMOJyNahslnVhThGeOxuOs8q/0/Ut5tHkeJx8AulancWOSbO2uKeTnD7dOmx6YxL3Wuw78krJIj1sfmWLHT2RwHcrwUbF3qBEHhLEzcum6J9KxqBnZGzuKW8yg2ezqfRh9wPlNUsgS7DTqeztJZE34mILkVfXCuKgfLZq7Pqkcbi1IcxCOgbeVdbHvG3GL7o1woET9TK2g4A1WwUZeQFh0uZnpdWRlDCM9eQ56Sk4TUcNSTfj3ECvhzAyfNi2xSDZ1QJQp4eQ27UwFElzySIgvjH4YhP4tceKS7jZbXj61/oV10UzRaS3bw1NcpYBAZ1IoNsRO4nP8ORcfl0jV7v5i1Bl5uHbpWTqtqowuzll5oely4C+umIj/+c4qVw83RVO+CJioT2SqZm9HKkb+Go3aqWMkYZi4w=
domain: null
path: /
expiry: null
max age: -1
Response string = {"SecurityName":"paul","UniqueID":"user:defaultWIMFileBasedRealm/uid=paul,o=defaultWIMFileBasedRealm","DisplayName":"paul","Groups":["staff","BogusGroup1","BogusGroup2"]}
Response:
Security name: paul
Unique ID: user:defaultWIMFileBasedRealm/uid=paul,o=defaultWIMFileBasedRealm
Groups:
Group name: staff
Group name: BogusGroup1
Group name: BogusGroup2
Waiting 6 minutes for LTPA token to expire ...
Done waiting.
Added LTPA cookie to CC request builder.
CC Response status = 401
LTPA cookie failed ... re-authenticating.
Credential Response status = 200
Credential Response has an entity.
Cookie key: LtpaToken2
name: LtpaToken2
value: 22atdzU2HnAmO7Oy2A4oPDMiDqSWP1E2DFgFeV/TuouSgxfNRl8YRHqa+2qTHeYyXGUNUc3dGfAu1eMu/BR9DUxUDdR9I0r4Q5LiqDoHeVhROIHqo3d0xgTMfmDoR47x5Xnh/enKV7p72yP+X5/fJ6lAeo0jHWzxyS6s10iX7PFZ9DPUOdQ0zURaL0AIsKikyFGQcVBP3VyfgrnpWWUoe6Ig0tFk1OGKYPcNRCL+PAAYf7TPs+SoI98ZvTPb+Ee4UICBujz2RX+t/MG5OgyE7ZwBVVKZwpBSzIfU3LW6dx6DoCX7436tAPKW8b8d7aDfB+bBFjhop+WtVeUnyGGGVqcHnQfvNw2lI4g/sDSSXXMJ5p0zx82YmlqxPIDhMfhxmlJJ1eGdjQLBmP0A9pxDguKTAMHtpGVDjV6+pWevgxNldAfcJ3oBhHOURrUAWMVlVgPm+7PzA5Ib9D7ETiKAaAAoghBZA/sZsMqq68jtFfcwQp+vXNBGeQnCRzlooNPBUmO9TvsPqKjaLOe2u0r2UUS14N+b5/nAbXjRZfBrKogM5FYAnPW7O0AYn1O6cTbHf9Y34feHkvUBDi7n/nIqRywZYYga729vXF/sK6P0VXYB9xTK7TXyBH4/klCv2V35ZJRDaMVsXdb1X1uFzo+6BZC9VTKmFeD7V3srP9K7X5U=
domain: null
path: /
expiry: null
max age: -1
Response string = {"SecurityName":"paul","UniqueID":"user:defaultWIMFileBasedRealm/uid=paul,o=defaultWIMFileBasedRealm","DisplayName":"paul","Groups":["staff","BogusGroup1","BogusGroup2"]}
Response:
Security name: paul
Unique ID: user:defaultWIMFileBasedRealm/uid=paul,o=defaultWIMFileBasedRealm
Groups:
Group name: staff
Group name: BogusGroup1
Group name: BogusGroup2
Added LTPA cookie to CC request builder.
CC Response status = 200
CC Response has an entity.
CC Response string = {"CCNo":"g4926032","AcctNo":"d392492","FirstName":"John","LastName":"Smith","Balance":"100"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment