Learn how to use appSecurity, LTPA (Lightweight Third Party Authentication), and Json Web Token (JWT) to secure a web application.
appSecurity LTPA (Lightweight Third Party Authentication) Json Web Token (JWT)
Configuration
<basicRegistry id="basic" realm="WebRealm">
<user name="bob" password="{xor}Lyg7" /> <!-- pwd -->
<user name="alice" password="{xor}PjM2PDovKDs=" /> <!-- alicepwd -->
<user name="carl" password="{xor}PD4tMy8oOw==" /> <!-- carlpwd -->
<group name="myAdmins">
<member name="bob" />
</group>
<group name="myUsers">
<member name="bob" />
<member name="alice" />
<member name="carl" />
</group>
</basicRegistry>
<application location="io.openliberty.guides.eventapp.war" type="war"
id="io.openliberty.guides.eventapp" name="io.openliberty.guides.eventapp"
context-root="/">
<application-bnd>
<security-role name="eventAdministrator">
<group name="myAdmins" />
</security-role>
<security-role name="registeredUser">
<group name="myUsers" />
</security-role>
</application-bnd>
</application>
web.xml
<security-role>
<role-name>eventAdministrator</role-name>
</security-role>
<security-role>
<role-name>registeredUser</role-name>
</security-role>
<!-- SECURITY CONSTRAINTS -->
<security-constraint>
<web-resource-collection>
<web-resource-name>ViewUsers</web-resource-name>
<url-pattern>/event/users</url-pattern>
<http-method>GET</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>eventAdministrator</role-name>
</auth-constraint>
</security-constraint>
<!-- AUTHENTICATION METHOD: Basic authentication -->
<!-- <login-config> <auth-method>BASIC</auth-method> </login-config> -->
<login-config id="LoginConfig_1">
<auth-method>FORM</auth-method>
<realm-name>WebRealm</realm-name>
<form-login-config id="FormLoginConfig_1">
<form-login-page>/login.jsf</form-login-page>
<form-error-page>/loginerror.jsf</form-error-page>
</form-login-config>
</login-config>
Front-End: see login and logerror files
LoginBean:
Authentication by request.login(this.j_username, this.j_password);
public String doLogIn() {
HttpServletRequest request = SessionUtils.getRequest();
// do filter
if (revokeList.contains(j_username)) {
System.out.println("User is blocked.");
pageDispatcher.showLogBlocked();
return "eventmanager.jsf";
}
// do login
try {
request.login(this.j_username, this.j_password);
} catch (ServletException e) {
//context.addMessage(null, new FacesMessage("Login failed."));
System.out.println("Login failed.");
pageDispatcher.showLogError();
return "eventmanager.jsf";
}
}
Authorization can be achieved after login:
``` // to get remote user using getRemoteUser() String remoteUser = request.getRemoteUser(); String role = getRole(request); System.out.println("AFTER LOGIN, REMOTE USER: " + remoteUser + " " + role);
// update session if (remoteUser != null && remoteUser.equals(j_username)){ buildJWT(request, j_username, j_password, role); updateSessionUser(request, j_username, j_password, role); } else { System.out.println("Update Sessional User Failed."); } //System.out.println("LTPA cookie" + getSecurityTokenLiberty()); //consumeJWT();
pageDispatcher.showMainPage(); return "eventmanager.jsf"; ```
public static String getUserInfoUsingLTPAtoken() {
ClientBuilder cb = ClientBuilder.newBuilder();
Client c = cb.build();
c.property("com.ibm.ws.jaxrs.client.ltpa.handler", "true");
String res = null;
res = c.target("http://localhost:" + port + "/event/users/token").request()
.get().readEntity(String.class);
c.close();
return res;
}
/* Sample code to retrieve LTPA token on the IBM WebSphere Liberty Profile */
/* @return an LTPA token */
public String getSecurityTokenLiberty() {
Cookie cookie = null;
String token = null;
try {
cookie = WebSecurityHelper.getSSOCookieFromSSOToken();
if (cookie != null) {
System.out.println(cookie.getName());
token = cookie.getValue();
}
} catch (Exception e) {
token = "no token found";
e.printStackTrace();
}
return token;
}
https://www.ibm.com/support/knowledgecenter/en/SSEQTP_liberty/com.ibm.websphere.wlp.doc/ae/twlp_sec_build_jwt.html https://www.ibm.com/support/knowledgecenter/SSEQTP_liberty/com.ibm.websphere.liberty.autogen.nd.doc/ae/rwlp_config_jwtBuilder.html?view=kc https://www.ibm.com/support/knowledgecenter/was_beta/com.ibm.websphere.wlp.nd.multiplatform.doc/ae/twlp_sec_json.html https://github.com/WASdev/sample.microservices.security.jwt/blob/master/liberty-jee-rp/src/main/resources/server.xml
https://www.eclipse.org/community/eclipse_newsletter/2017/september/article2.php https://tools.ietf.org/html/rfc7519#section-3
<keyStore id="defaultKeyStore" password="app-pass"
location="${server.config.dir}/key.jks" />
<!-- <keyStore id="defaultTrustStore" password="trust-pass"
location="${server.config.dir}/truststore.jks" /> -->
<!-- Configure the default keystore to trust the OP -->
<!-- <ssl id="defaultSSLConfig" keyStoreRef="defaultKeyStore"
trustStoreRef="defaultTrustStore" serverKeyAlias="jwtsampleapp" /> -->
<jwtBuilder id="jwtBuilder"
jwkEnabled="false"
keyStoreRef="defaultKeyStore"
keyAlias="jwtsampleapp"
/>
<!-- <jwtConsumer id="jwtConsumer"
signatureAlgorithm="RS256"
issuer="http://localhost:9080/jwtBuilder"
trustStoreRef="defaultTrustStore"
trustedAlias="jwtsampleapp"
/> -->
<!-- <mpJwt id="mpjwt"
issuer="http://localhost:9080/jwtBuilder"
audiences="http://localhost:9080/event/jwt">
</mpJwt> -->
private void buildJWT(HttpServletRequest request, String username, String password, String role) {
try {
JwtBuilder jwtBuilder = JwtBuilder.create();
jwtBuilder.subject(username).claim(Claims.AUDIENCE, "http://localhost:9080/event/jwt").claim("iss","http://localhost:9080/jwtBuilder" ).claim("alg","RS256" ).claim("username", username).claim("password", password).claim("role", role);
JwtToken goToken = jwtBuilder.buildJwt();
String newJwt = goToken.compact();
System.out.println("Writer Interceptor added token :: "+newJwt);
// get the current session
HttpSession ses = request.getSession(false);
if (ses == null) {
System.out.println("Session is timeout.");
}
ses.setAttribute("jwt", newJwt); // important to set it here!
} catch (InvalidClaimException e) {
System.out.println("InvalidClaimException");
e.printStackTrace();
} catch (JwtException e) {
System.out.println("JwtException");
e.printStackTrace();
} catch (InvalidBuilderException e) {
System.out.println("InvalidBuilderException");
e.printStackTrace();
}
}
To see the new application in action, run the Maven liberty:start-server
command from the start
directory:
$ mvn liberty:start-server