In the initial stages I have been creating JWT Token manually, which expires in a week. After our testing now I would like to automate the JWT Token creation process using a Http Rest call. I don’t see any documentation on how to automate the JWT Token creation process. Any pointers or link towards this topic will be helpful.
In python, I use the pyjwt library to generate a unique token each time a request is made. This token is sent as a Bearer Token in an authorization header of the request. I store the API Key & Secret in a secrets.py file. For example:
import jwt
import requests
import secrets
import json
from time import time
# create a function to generate a token using the pyjwt library
def generateToken():
token = jwt.encode(
# Create a payload of the token containing API Key & expiration time
{"iss": API_KEY, "exp": time() + 5000},
# Secret used to generate token signature
API_SECRET,
# Specify the hashing alg
algorithm='HS256'
# Convert token to utf-8
).decode('utf-8')
return token
# send a request with headers including a token
def getUsers():
headers = {'authorization': 'Bearer %s' % generateToken(),
'content-type': 'application/json'}
r = requests.get('https://api.zoom.us/v2/users/', headers=headers)
print(r.text)
In Node.js, you can use the jsonwebtoken package to create these tokens in similar ways. I use dotenv to store the API Key & Secret.
require("dotenv").config();
const jwt = require("jsonwebtoken");
const fetch = require("node-fetch");
const generateToken = () => {
// create a payload with the issuer and expiration time
const payload = {
iss: process.env.API_KEY,
exp: new Date().getTime() + 5000,
};
// sign the token using your API Secret
const token = jwt.sign(payload, process.env.API_SECRET);
return token;
};
const getUsers = async () => {
// send a request with a token in the authorization header
let url = "https://api.zoom.us/v2/users";
let headers = { headers: { Authorization: `Bearer ${getToken()}` } };
try {
const response = await fetch(url, headers);
return json = await response.json();
} catch (error) {
console.log(error);
}
};
import java.util.Date;
import java.util.UUID;
@SuppressWarnings("deprecation")
public String createJWTToken() {
String id = UUID.randomUUID().toString().replace("-", "");
//The JWT signature algorithm we will be using to sign the token
final SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
//We will sign our JWT with our ApiKey secret
//Let's set the JWT Claims
JwtBuilder builder = null;
try {
builder = Jwts.builder().setId(id).setHeaderParam("typ", "JWT")
.setIssuedAt(now)
.setSubject("")
.setIssuer(API_KEY)
.signWith(signatureAlgorithm, SECRET_KEY.getBytes("UTF-8"));
//if it has been specified, let's add the expiration
if (ttlMillis >= 0) {
long expMillis = nowMillis + ttlMillis;
Date exp = new Date(expMillis);
builder.setExpiration(exp);
}
} catch (Exception e) {
e.printStackTrace();
}
return builder.compact();//Builds the JWT and serializes it to a compact, URL-safe string
}
Below is the exception for JWT token creation
javax.servlet.ServletException: Servlet execution threw an exception
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:328)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at com.test.lms.servlets.GlobalFilter.doFilter(GlobalFilter.java:204)
at com.test.lms.servlets.GlobalFilter.doFilter(GlobalFilter.java:48)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at com.general.FilterDemo.doFilter(FilterDemo.java:312)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.ajp.AjpProcessor.process(AjpProcessor.java:200)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source) Caused by: java.lang.NoClassDefFoundError: io/jsonwebtoken/Jwts
at com.zoom.JWTTokenGeneration.createJWTToken(JWTTokenGeneration.java:31)
at com.zoom.Utilities.setMeeting(Utilities.java:571)
at com.general.InsertController.doPost(InsertController.java:377)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) ... 22 more Caused by: java.lang.ClassNotFoundException: io.jsonwebtoken.Jwts
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1701)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1546) ... 28 more
@tommy : The jar present on a different path on my machine and now jar is placed in classes/lib folder. works perfectly. Once again thanks for the help
Hi @gsura I don’t know a method to generate these tokens natively in cURL. I would use one of these libraries to generate the tokens which can be accessed by a cURL request.