First time I'm in the tokens, I'm using jwt in java. I manage to generate the token without problems, I send it as a parameter to a servlet through a url and I show it.
What is not done, is how I should verify that the token has not expired. How could I do it? Thank you very much already.
servlet code
@WebServlet("/hola")
public class hi extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// obtengo parametro que viene en el request
String t = req.getParameter("token");
PrintWriter out = resp.getWriter();
out.println("<html><body>");
// Muestro parametro
out.println("Token : " + t);
out.println("</body></html>");
out.close();
}
}
Method that generates a token
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
Key key = MacProvider.generateKey(signatureAlgorithm);
private String createJWT(String id, String issuer, String subject, long ttlMillis) {
//We will sign our JWT with our ApiKey secret
byte[] apiKeySecretBytes = key.getEncoded();
Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
//Let's set the JWT Claims
JwtBuilder builder = Jwts.builder().setId(id)
.setIssuedAt(now)
.setSubject(subject)
.setIssuer(issuer)
.signWith(signatureAlgorithm, signingKey);
//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);
}
//Builds the JWT and serializes it to a compact, URL-safe string
return builder.compact();
}