· 6 years ago · Sep 26, 2019, 02:54 PM
1package DataClasses.JWToken;
2
3import io.jsonwebtoken.*;
4
5import javax.crypto.spec.SecretKeySpec;
6import javax.xml.bind.DatatypeConverter;
7import java.io.IOException;
8import java.security.Key;
9import java.util.Date;
10import java.util.Map;
11
12public class JsonWebToken {
13 private String key = "secret_key";
14 private String jwt;
15
16 public JsonWebToken(){
17 this.jwt = null;
18 }
19
20 public String CreateJsonWebToken(String id, String isuser, String subject, long ttlMillis){
21//The JWT signature algorithm we will be using to sign the token
22 SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
23
24 long nowMillis = System.currentTimeMillis();
25 Date now = new Date(nowMillis);
26
27//We will sign our JWT with our ApiKey secret
28 byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(key);
29 Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
30
31 Header header = Jwts.header();
32 header.setType("JWT");
33
34 JwtBuilder builder = Jwts.builder().setHeader((Map<String, Object>)
35 header).setId(id)
36 .setIssuedAt(now)
37 .setSubject(subject)
38 .setIssuer(isuser)
39 .signWith(signatureAlgorithm, signingKey);
40
41//if it has been specified, let's add the expiration
42 if (ttlMillis >= 0) {
43 long expMillis = nowMillis + ttlMillis;
44 Date exp = new Date(expMillis);
45 builder.setExpiration(exp);
46 }
47
48//Builds the JWT and serializes it to a compact, URL-safe string
49 return builder.compact();
50 }
51
52 public String ParseJsonWebToken(String jwt) {
53 try {
54 //This line will throw an exception if it is not a signed JWS (as expected)
55 Claims claims = Jwts.parser()
56 .setSigningKey(DatatypeConverter.parseBase64Binary(key))
57 .parseClaimsJws(jwt).getBody();
58
59 System.out.println("ID: " + claims.getId());
60 System.out.println("Subject: " + claims.getSubject());
61 System.out.println("Issuer: " + claims.getIssuer());
62 System.out.println("Expiration: " + claims.getExpiration());
63
64 String r = "ID: " + claims.getId() + " Subject: " + claims.getSubject() + " Issuer: " + claims.getIssuer() + " Expiration: " + claims.getExpiration();
65 return r;
66 }
67 catch (ExpiredJwtException eje){
68 return "not signed token";
69 }
70 }
71
72 public String JWT_get_ID(String jwt)throws IOException {
73 try {
74 //This line will throw an exception if it is not a signed JWS (as expected)
75 Claims claims = Jwts.parser()
76 .setSigningKey(DatatypeConverter.parseBase64Binary(key))
77 .parseClaimsJws(jwt).getBody();
78
79 return claims.getId();
80 }
81 catch (ExpiredJwtException eje){
82 return "not signed token";
83 }
84 }
85}