- jwt decoding without a key
This commit is contained in:
@@ -17,6 +17,6 @@ dependencies {
|
||||
runtimeOnly("io.jsonwebtoken:jjwt-impl:0.12.5")
|
||||
runtimeOnly("io.jsonwebtoken:jjwt-jackson:0.12.5")
|
||||
|
||||
// another library
|
||||
// another library, good for a client side
|
||||
implementation("com.auth0:java-jwt:4.4.0")
|
||||
}
|
||||
|
||||
@@ -25,12 +25,15 @@ public class Jwt0Sample {
|
||||
.withSubject("Hello")
|
||||
.sign(Algorithm.HMAC256(key));
|
||||
}
|
||||
public static DecodedJWT parseToken(String token){
|
||||
public static DecodedJWT parseToken(String token, byte[] key){
|
||||
return JWT.require(Algorithm.HMAC256(key))
|
||||
.withIssuer("Elex")
|
||||
.build()
|
||||
.verify(token);
|
||||
}
|
||||
public static DecodedJWT parseToken(String token){
|
||||
return JWT.decode(token);
|
||||
}
|
||||
|
||||
public static void main(String... args){
|
||||
String token = genToken();
|
||||
|
||||
@@ -76,6 +76,25 @@ public class JwtsSample {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
public static String decodeToken(final String token) throws JwtException {
|
||||
String[] chunks = token.split("\\.");
|
||||
Base64.Decoder decoder = Base64.getUrlDecoder();
|
||||
|
||||
String header = new String(decoder.decode(chunks[0]));
|
||||
String payload = new String(decoder.decode(chunks[1]));
|
||||
|
||||
return payload;
|
||||
|
||||
|
||||
}
|
||||
public static String decodeToken2(final String token) throws JwtException {
|
||||
String s = Jwts.parser().unsecured().build().parseSignedClaims(token)
|
||||
.getPayload().getSubject();
|
||||
|
||||
return s;
|
||||
|
||||
|
||||
}
|
||||
|
||||
public static String parseToken(final String token, final PublicKey key) throws JwtException {
|
||||
try {
|
||||
|
||||
@@ -26,7 +26,25 @@ import java.util.Random;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class SampleTest {
|
||||
@Test
|
||||
void test2(){
|
||||
final SecretKey signingKey = Jwts.SIG.HS384.key().build();
|
||||
String token = Jwts.builder()
|
||||
.header().type("JWT")
|
||||
.and()
|
||||
.issuer("Elex")
|
||||
.expiration(Date.from(Instant.now().plus(3, ChronoUnit.HOURS)))
|
||||
.claim("userId", 3)
|
||||
.subject("hello")
|
||||
.signWith(signingKey)
|
||||
.compact();
|
||||
String payload = JwtsSample.decodeToken(token);
|
||||
|
||||
System.out.println(payload);
|
||||
|
||||
//String sub = JwtsSample.decodeToken2(token);
|
||||
//System.out.println(sub);
|
||||
}
|
||||
@Test
|
||||
void test() throws NoSuchAlgorithmException, InvalidKeySpecException {
|
||||
byte[] key = new byte[32];
|
||||
|
||||
Reference in New Issue
Block a user