Embedding in a Java app - example

Hi,

The embedding feature look nice. Currently 4 examples are given but for non Java application.
I tried to do insert the code in a java app by including the io.jsonwebtoken library?
I also used the org.json.JSONObject to build a json object.

// Fisrt, I create the Json object
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put(“dashboard”, “2”);
JSONObject jsonObject = new JSONObject();
jsonObject.put(“resource”, jsonObject1);
jsonObject.put(“params”, “”);

// Then my claims
Claims claims2 = Jwts.claims();
claims2.put(“payload”,jsonObject.toString());

//Finally the token
String token = Jwts.builder()
.setClaims(claims2)
.signWith(SignatureAlgorithm.HS256, METABASE_SECRET_KEY)
.compact();

//then, I insert my iframeUrl string.
String iframeUrl = METABASE_SITE_URL + “/embed/dashboard/” + token + “#bordered=true&titled=true”;

When I load my page, I got a metabase feedback : “Message seems corrupt or manipulated.”

Claims 2 generated by the program : {payload={“resource”:{“dashboard”:“2”},“params”:""}}
If I do a java - claims.get(“payload”); - , I get : {“resource”:{“dashboard”:“2”},“params”:""}

Everything looks ok. I do not understand why it is not working. I have check my metabase_secret_key, that the embedded dashboard is published …

Did anyone succeed to embed a dashboard in a java app ? If yes, help is welcome.

Thanks in advance,

FBS

Dear all,

After searching and searching, I finally change of library going to the org.jose4j library. I could not find why it was not working but now, everything is working well. Below my code for Java embedding. Hope it can help you.

JSONObject jsonObject1 = new JSONObject();
jsonObject1.put(“dashboard”, 2);
JSONObject jsonObject = new JSONObject();
jsonObject.put(“resource”, jsonObject1);
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put(“category”, “Widget”);
jsonObject.put(“params”,jsonObject2);

    JwtClaims claims = new JwtClaims();
    
    // Set Key
    Key key = null;
	try {
		key = new HmacKey(METABASE_SECRET_KEY.getBytes("UTF-8"));
	} catch (UnsupportedEncodingException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
    JsonWebSignature jws = new JsonWebSignature();
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
    jws.setKey(key);
    jws.setPayload(jsonObject.toString());
    jws.setDoKeyValidation(false); // relaxes the key length requirement
    String jwt = null;
	try {
		jwt = jws.getCompactSerialization();
	} catch (JoseException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	String iframeUrl = METABASE_SITE_URL + "/embed/dashboard/" + jwt + "#bordered=true&titled=true";
             embedded1.setSource(iframeUrl);

Where embedded is my container and setsource the function to set the source.
Of course, you need to setup your METABASE_SITE_URL and METABASE_SECRET_KEY.
FBS

2 Likes

Had the similar problem with nimbusd library, and reverted back to the org.jose4 library and I seem to be getting further with embedded setup

Spring MVC example:

2 Likes

Hi @fbeaufil, good morning!

Could you tell us what the “imports” of this Java class are?

I’m trying to implement here.

Regards,
Lourival Oliveira

public String getMetabaseEmbeddedUrl(String metabaseSecretKey, Map<String, Object> payload, String metabaseUrl)

{

// Need to encode the secret key 
String metaBaseEncodedSecretKey = Base64.getEncoder().encodeToString(metabaseSecretKey.getBytes());
    String jwtToken = Jwts.builder()
            .setHeaderParam("typ", "JWT")
            .setClaims(payload)
            .signWith(SignatureAlgorithm.HS256, metaBaseEncodedSecretKey)
            .setIssuedAt(new Date())
            .compact();
    return metabaseUrl + "/embed/dashboard/" + jwtToken;
}
1 Like

here is an example I assembled based on the posting at https://www.coderslexicon.com/generating-json-web-tokens-jwt-in-java-or-php/ .
This uses only a few more generic imports and is quite short, which I like a lot.
Maybe finally, an example of this or another implementation could be added to the examples at Metabase repository...

package my.jwt.package;

import java.util.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 *
 * @author via https://www.coderslexicon.com/generating-json-web-tokens-jwt-in-java-or-php/
 */
public class JWTToken {

 /**
  * Helper method that generates a JWT token with HS256 algorithm
  *
  * @param header    header of the token
  * @param payload   payload in JSON format
  * @param secretKey secret used for encoding.
  * @return String in JWT format
  */
 public String CreateHS256JWT(String header, String payload, String secretKey) {

  // encode header
  String base64UrlHeader = Base64.getUrlEncoder().withoutPadding().encodeToString(header.getBytes());

  // encode payload
  String base64UrlPayload = Base64.getUrlEncoder().withoutPadding().encodeToString(payload.getBytes());

  // encode secret key
  try {
   String base64UrlSignature = hmacEncode(base64UrlHeader + "." + base64UrlPayload, secretKey);

   return base64UrlHeader + "." + base64UrlPayload + "." + base64UrlSignature;
  } catch (Exception e) {
   throw new RuntimeException("Unable to generate a JWT token.");
  }

 }

 /**
  * Helper method that encodes data using HmacSHA256 and key.
  *
  * @param data data to encode
  * @param key  Secret key used during encoding.
  * @return Base64UrlEncoded string without padding
  */
 private static String hmacEncode(String data, String key) throws Exception {
  Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
  SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(), "HmacSHA256");
  sha256_HMAC.init(secret_key);

  return Base64.getUrlEncoder().withoutPadding().encodeToString(sha256_HMAC.doFinal(data.getBytes()));
 }

}