Create a valid JWT token with a Private_Key.p8 in React

Hello community,

I am trying to access apple connect API by creating a valid JWT token with a given AuthKey_Key_ID.p8, but I don't seem to be able to parse this file neither with fs.readFileSync("path/to/key.p8") nor with OpenSSL.Pkey.read(File.read("path/to/key.p8").

I found various example that were working between 2018 and 2019, but none that is recent and has some clear guidelines or documentation.

below is some of the code as I have it now:

const ReportsComponent = () => {

  const now = Math.round(new Date().getTime() / 1000);
  const expirationTime = now + 1999;

  const privateKey = OpenSSL.Pkey.read(
    File.read("PATH/TO/PRIVATEKEY.p8")
  );

  const headers = {
    algorithm: "ES256",
    header: {
      alg: "ES256",
      kid: "KEY ID",
      typ: "JWT",
    },
  };

  const payload = {
    iss: "ISSUER_ID",
    exp: expirationTime,
    aud: "appstoreconnect-v1",
  };

  const token = jwt.sign(payload, privateKey, headers);
  console.log("token ---> " + token);

  let options = {
    host: "my link to heroku cors app",
    path: "https://api.appstoreconnect.apple.com/v1/apps",
    method: "GET",
    headers: {
      Accept: "application/a-gzip, application/json",
      Authorization: `Bearer ${token}`,
    },
  };

  let req = https.request(options, function (res) {
    console.log("Status: " + res.statusCode);
    console.log("Header: " + JSON.stringify(res.headers));
    res.setEncoding("utf8");
    res.on("data", function (chunk) {
      console.log("Body: " + chunk);
    });
    res.on("error", function (error) {
      console.log("connection could not be made " + error.message);
    });
  });

  req.end();

  return (
    ...
  );
};

export default ReportsComponent;
Create a valid JWT token with a Private_Key.p8 in React
 
 
Q