-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathExample.java
More file actions
80 lines (66 loc) · 2.59 KB
/
Copy pathExample.java
File metadata and controls
80 lines (66 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.example.JwtTest;
import java.io.*;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;
import java.util.Optional;
import javax.crypto.KeyGenerator;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
@WebServlet(name = "JwtTest1", value = "/Auth")
public class auth0 extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// OK: first decode without signature verification
// and then verify with signature verification
String JwtToken1 = request.getParameter("JWT1");
String userName = decodeToken(JwtToken1);
verifyToken(JwtToken1, "A Securely generated Key");
if (Objects.equals(userName, "Admin")) {
out.println("<html><body>");
out.println("<h1>" + "heyyy Admin" + "</h1>");
out.println("</body></html>");
}
out.println("<html><body>");
out.println("<h1>" + "heyyy Nobody" + "</h1>");
out.println("</body></html>");
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// NOT OK: only decode, no verification
String JwtToken2 = request.getParameter("JWT2");
String userName = decodeToken(JwtToken2);
if (Objects.equals(userName, "Admin")) {
out.println("<html><body>");
out.println("<h1>" + "heyyy Admin" + "</h1>");
out.println("</body></html>");
}
// OK: no clue of the use of unsafe decoded JWT return value
JwtToken2 = request.getParameter("JWT2");
JWT.decode(JwtToken2);
out.println("<html><body>");
out.println("<h1>" + "heyyy Nobody" + "</h1>");
out.println("</body></html>");
}
public static boolean verifyToken(final String token, final String key) {
try {
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(key)).build();
verifier.verify(token);
return true;
} catch (JWTVerificationException e) {
System.out.printf("jwt decode fail, token: %s", e);
}
return false;
}
public static String decodeToken(final String token) {
DecodedJWT jwt = JWT.decode(token);
return Optional.of(jwt).map(item -> item.getClaim("userName").asString()).orElse("");
}
}