0% found this document useful (0 votes)
3 views3 pages

Sample JWT Client Code Example

The document provides sample client code for implementing JWT authentication using Java APIs, specifically utilizing the JJWT library. It includes a class that demonstrates how to create a JWT token, set its expiration, and make a RESTful call to a login status endpoint. Additionally, it outlines methods for handling responses and converting user groups to JSON format.

Uploaded by

nauticaltd
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views3 pages

Sample JWT Client Code Example

The document provides sample client code for implementing JWT authentication using Java APIs, specifically utilizing the JJWT library. It includes a class that demonstrates how to create a JWT token, set its expiration, and make a RESTful call to a login status endpoint. Additionally, it outlines methods for handling responses and converting user groups to JSON format.

Uploaded by

nauticaltd
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

2/18/25, 1:26 PM Sample Client Code

SPECTRUM™ 8.3.1, January 2024

You are here: Web Services Guide > Web Services Security > JWT Authentication for REST > Sample Client Code

Sample Client Code

There are Java APIs available that can create the JWT token based on provided information. The code is using the
Java JWT: JSON Web Token for Java and Android (JJWT) jar.

The following is a sample JWT Login client: Copy

package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
/**
* Sample JWT Client code
*
* @author Shaw Systems
*/
public class SampleJWTClient {
private String userName;
private List<String> userGroups;
public void doJWTLogin(){
//TODO get user name and User Groups from data source.
List<String> groups = [Link];
String userName = [Link];
//Create token
JwtBuilder builder = [Link]();
[Link](userName);
[Link](SignatureAlgorithm.RS512, getKey());
//TODO set the token expiry time
//Sample code sets the token expiry to 6 hours.
Calendar calendar = [Link]();
[Link](Calendar.HOUR_OF_DAY, 6);
Date expiration = [Link]();
[Link](expiration);
//TODO set correct company name as issuer
[Link]("<COMPANY NAME>");
[Link]("spectrum");
[Link]("groups", toJsonArray(groups));
AccessTokenDTO dto = new AccessTokenDTO();
[Link]([Link]());
//Make Call
ResponseEntity<String> returnType = getResponse(dto);
//Verify return
String spectrumToken = null;
[Link] 1/3
2/18/25, 1:26 PM Sample Client Code
try{
if ([Link]([Link]())) {
LoginResource resource = getMappedResource([Link]());
log("response status=" + [Link]());
if("RESPONSE_ERROR".equals([Link]())){
if([Link]()!=null){
StringBuilder errorMessage = new StringBuilder();
for(String msg: [Link]()){
[Link](msg + "\n");
}
log("JWT Login Failed. Error message returned from server " +
[Link]());
}
}else{
spectrumToken = [Link]().getSpectrumToken();
log("Returned spectrum token " + spectrumToken);
}
} else {
log("JWT Login failed. HTTP Status returned from call " + [Link]());
}
}catch(Exception e){
[Link]();
}
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
[Link] = userName;
}
public List<String> getUserGroups() {
return userGroups;
}
public void setUserGroups(List<String> userGroups) {
[Link] = userGroups;
}
/**
* Converts the Web Service JSON response to a java object
* @param response
* @return
*/
public LoginResource getMappedResource(String response){
LoginResource resource = null;
ObjectMapper aMapper = new ObjectMapper();
try {
resource = [Link](response, [Link]);
} catch (Exception e) {
log("Exception raised....e=" + [Link]());
[Link]();
}
return resource;
}
private static void log(String message) {
[Link](message);
}
/**
* Converts java List to JSON array
*
* @param list
* @return
*/
private String toJsonArray(List<String> list) {
String jsonArray = null;
try (final StringWriter sw = new StringWriter()) {
final ObjectMapper mapper = new ObjectMapper();
[Link](sw, list);
jsonArray = [Link]();//use toString() to convert to JSON
} catch(IOException e) {
log("IOException while creating JSON object" + [Link]());
}
return jsonArray;
}
/**
* Gets the key to sign the JWT token
*
* @return
*/
private Key getKey() {
Key key = null;
//TODO: set keystore file, alias and password to read the key
String keystoreFileName = "jwt_keystore";

[Link] 2/3
2/18/25, 1:26 PM Sample Client Code
String keyPassword = "Spectrum";
String keyAlias = "spectrumjwtkey";
try {
//Get the key from the keystore file
KeyStore keystore = [Link]([Link]());
try (FileInputStream keystoreFile = new FileInputStream(keystoreFileName)) {
[Link](keystoreFile, [Link]());
}
key = [Link](keyAlias, [Link]());
} catch (UnrecoverableKeyException | KeyStoreException | NoSuchAlgorithmException |
CertificateException
| IOException e) {
log("Error retrieving the key for decrypting JWT " + [Link]());
[Link]();
return null;
}
return key;
}
public static <T> ResponseEntity<String> getResponse(AccessTokenDTO entityBody){
ResponseEntity<String> returnType = null;
//TODO Change it to the URL of the installation
String spectrumURL = "[Link]
String restfulUrl = "rws/pub/jwt/loginstatus";
String spectrumRestfulUrl = spectrumURL + restfulUrl;
RestTemplate restTemplate = new RestTemplate();
try
{
HttpHeaders headers = new HttpHeaders();
[Link]("Accept", MediaType.APPLICATION_JSON.toString());
[Link]("Accept-Language", [Link]());
HttpEntity<AccessTokenDTO> entity = new HttpEntity<AccessTokenDTO>(entityBody,
headers);
log("Calling Restful service ");
returnType = [Link](spectrumRestfulUrl,
[Link], entity, [Link], new HashMap<String, Object>() ;
log(" Restful service completed @: " + ([Link]()));
return returnType;
} catch (Exception e)
{
String errorMessage = "Got exception from the restful uri: " + spectrumRestfulUrl + "
error=" + [Link]();
log(errorMessage);
HttpHeaders headers = new HttpHeaders();
[Link]("Accept", MediaType.APPLICATION_JSON.toString());
HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
if ([Link]("401") > -1) {
status = [Link];
}
return (new ResponseEntity<String>(errorMessage, headers, status));
}
}
}

Copyright © 2024 Shaw Systems Associates, LLC. All Rights Reserved. Restricted/Confidential

[Link] 3/3

You might also like