- jwt decoding without a key

This commit is contained in:
2024-02-24 10:56:40 +09:00
parent 805816491a
commit 13f2867f99
4 changed files with 42 additions and 2 deletions

View File

@@ -17,6 +17,6 @@ dependencies {
runtimeOnly("io.jsonwebtoken:jjwt-impl:0.12.5") runtimeOnly("io.jsonwebtoken:jjwt-impl:0.12.5")
runtimeOnly("io.jsonwebtoken:jjwt-jackson: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") implementation("com.auth0:java-jwt:4.4.0")
} }

View File

@@ -25,12 +25,15 @@ public class Jwt0Sample {
.withSubject("Hello") .withSubject("Hello")
.sign(Algorithm.HMAC256(key)); .sign(Algorithm.HMAC256(key));
} }
public static DecodedJWT parseToken(String token){ public static DecodedJWT parseToken(String token, byte[] key){
return JWT.require(Algorithm.HMAC256(key)) return JWT.require(Algorithm.HMAC256(key))
.withIssuer("Elex") .withIssuer("Elex")
.build() .build()
.verify(token); .verify(token);
} }
public static DecodedJWT parseToken(String token){
return JWT.decode(token);
}
public static void main(String... args){ public static void main(String... args){
String token = genToken(); String token = genToken();

View File

@@ -76,6 +76,25 @@ public class JwtsSample {
throw e; 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 { public static String parseToken(final String token, final PublicKey key) throws JwtException {
try { try {

View File

@@ -26,7 +26,25 @@ import java.util.Random;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
class SampleTest { 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 @Test
void test() throws NoSuchAlgorithmException, InvalidKeySpecException { void test() throws NoSuchAlgorithmException, InvalidKeySpecException {
byte[] key = new byte[32]; byte[] key = new byte[32];