The platform requires a JWT token consisting of a Header, Payload, and Signature. The signature must be generated using the appSecret provided by the platform via the HMAC-SHA256 algorithm.
Creation Steps:
- Create a Header object (specifying algorithm
HS256 and type JwtUtil). - Create a Payload object containing the required user fields.
- Base64 encode the Header and Payload.
- Generate a signature using the
appSecret and the encoded Header.Payload string. - Concatenate the three parts:
encodedHeader.encodedPayload.signature.
/**
* JWT Signature Implementation Example
*/
public class JwtUtil {
private static String SECRET_KEY = "appSecret"; // Replace with actual appSecret
private static String generateToken(String userEID, String userType, String schoolEID) {
// 1. Header
JSONObject header = new JSONObject();
header.put("alg", "HS256");
header.put("typ", "JwtUtil");
// 2. Payload
JSONObject payload = new JSONObject();
long timeMillis = System.currentTimeMillis() / 1000;
payload.put("userEID", userEID);
payload.put("userType", userType);
payload.put("schoolEID", schoolEID);
payload.put("sysTime", timeMillis);
// 3. Base64 Encoding
String encodedHeader = Base64.getEncoder().encodeToString((header.toString().getBytes()));
String encodedPayload = Base64.getEncoder().encodeToString((payload.toString().getBytes()));
// 4. Signature
String signature = generateSignature(SECRET_KEY, encodedHeader + "." + encodedPayload);
// 5. Final Token
return encodedHeader + "." + encodedPayload + "." + signature;
}
private static String generateSignature(String appSecret, String data) {
try {
byte[] secretKeyBytes = appSecret.getBytes();
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKeyBytes, "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(secretKeySpec);
byte[] signatureBytes = mac.doFinal(data.getBytes());
return Base64.getUrlEncoder().encodeToString(signatureBytes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String token = generateToken("13900001234", "1", "25320316");
System.out.println("Generated token: " + token);
}
}