Skip to content

Instantly share code, notes, and snippets.

@mattjtodd
Last active February 21, 2020 13:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattjtodd/5176da8e4c8b31b0f31e8f148c7bd4c9 to your computer and use it in GitHub Desktop.
Save mattjtodd/5176da8e4c8b31b0f31e8f148c7bd4c9 to your computer and use it in GitHub Desktop.
package uk.co.blackcat;
import com.google.common.hash.Hashing;
import io.jsonwebtoken.*;
import io.jsonwebtoken.lang.Maps;
import io.jsonwebtoken.security.Keys;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.util.Map;
public class HttpTest {
public static void main(String[] args) throws Exception {
signJwt();
}
private static void signJwt() throws NoSuchAlgorithmException, InvalidKeySpecException {
// This represents the JWK set which should be made available to clients via HTTPS
// https://tools.ietf.org/html/rfc7517
KeyPair keyPair = Keys.keyPairFor(SignatureAlgorithm.RS256);
String jwkId = Hashing.sha256().hashBytes(keyPair.getPublic().getEncoded()).toString();
// Create and sign our Boris
String jws = Jwts.builder()
.setHeaderParam(JwsHeader.KEY_ID, jwkId)
.setHeaderParam(JwsHeader.JWK_SET_URL, "The url for the JWK Set")
.setSubject("Boris")
.claim("status", "World King")
.signWith(keyPair.getPrivate())
.compact();
SigningKeyResolver signingKeyResolver = getSigningKeyResolver(jwkId, keyPair.getPublic());
// verify the message signature header using the public key.
Jws<Claims> claimsJws = Jwts.parserBuilder()
.setSigningKeyResolver(signingKeyResolver)
.build()
.parseClaimsJws(jws);
System.out.println(claimsJws.getHeader());
System.out.println(claimsJws.getBody());
}
private static SigningKeyResolver getSigningKeyResolver(String jwkId, PublicKey publicKey) {
return new SigningKeyResolver() {
Map<String, PublicKey> jwkSet = Maps.of(jwkId, publicKey).build();
@Override
public Key resolveSigningKey(JwsHeader jwsHeader, Claims claims) {
return jwkSet.get(jwsHeader.getKeyId());
}
@Override
public Key resolveSigningKey(JwsHeader jwsHeader, String s) {
return jwkSet.get(jwsHeader.getKeyId());
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment