- jwt store/restore key
This commit is contained in:
@@ -10,6 +10,7 @@ import io.jsonwebtoken.JwtException;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.security.KeyPair;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.PublicKey;
|
||||
@@ -28,6 +29,18 @@ public class JwtsSample {
|
||||
|
||||
}
|
||||
|
||||
public static byte[] getEncodedKey(SecretKey key) {
|
||||
return key.getEncoded();
|
||||
}
|
||||
|
||||
public static String getAlgorithmName(SecretKey key) {
|
||||
return key.getAlgorithm();
|
||||
}
|
||||
|
||||
public static SecretKey getSecretKey(byte[] encodedKey, String alg) {
|
||||
return new SecretKeySpec(encodedKey, alg);
|
||||
}
|
||||
|
||||
public static KeyPair generateKeyPair() {
|
||||
return Jwts.SIG.RS512.keyPair().build();
|
||||
|
||||
@@ -76,6 +89,7 @@ public class JwtsSample {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
public static String decodeToken(final String token) throws JwtException {
|
||||
String[] chunks = token.split("\\.");
|
||||
Base64.Decoder decoder = Base64.getUrlDecoder();
|
||||
@@ -87,6 +101,7 @@ public class JwtsSample {
|
||||
|
||||
|
||||
}
|
||||
|
||||
public static String decodeToken2(final String token) throws JwtException {
|
||||
String s = Jwts.parser().unsecured().build().parseSignedClaims(token)
|
||||
.getPayload().getSubject();
|
||||
|
||||
@@ -26,6 +26,31 @@ import java.util.Random;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class SampleTest {
|
||||
@Test
|
||||
void keyTest(){
|
||||
SecretKey secretKey = JwtsSample.generateSecretKey();
|
||||
|
||||
byte[] rawKey = secretKey.getEncoded();
|
||||
String alg = secretKey.getAlgorithm();
|
||||
|
||||
SecretKey secKey = JwtsSample.getSecretKey(rawKey, alg);
|
||||
|
||||
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(secretKey)
|
||||
.compact();
|
||||
|
||||
String subject = Jwts.parser()
|
||||
.verifyWith(secKey)
|
||||
.requireIssuer("Elex") // 토큰의 Issuer 일치 여부 확인
|
||||
.build().parseSignedClaims(token).getPayload().getSubject();
|
||||
System.out.println(subject);
|
||||
}
|
||||
@Test
|
||||
void test2(){
|
||||
final SecretKey signingKey = Jwts.SIG.HS384.key().build();
|
||||
|
||||
Reference in New Issue
Block a user