io.smallrye.jwt.KeyUtils Java Examples

The following examples show how to use io.smallrye.jwt.KeyUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KeyLocationResolverTest.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
@Test
public void testVerifyEcSignedTokenWithWrongKey() throws Exception {
    JwtClaimsBuilder builder = Jwt.claims("/Token1.json");
    builder.issuedAt(Instant.now().getEpochSecond());
    builder.expiresAt(Instant.now().getEpochSecond() + 300);
    String jwt = builder.sign(KeyUtils.readPrivateKey("/ecPrivateKey.pem", SignatureAlgorithm.ES256));
    JWTAuthContextInfoProvider provider = JWTAuthContextInfoProvider.createWithKeyLocation("publicKey.pem",
            "https://server.example.com");
    JWTAuthContextInfo contextInfo = provider.getContextInfo();
    contextInfo.setSignatureAlgorithm(SignatureAlgorithm.ES256);
    try {
        new DefaultJWTTokenParser().parse(jwt, contextInfo);
        Assert.fail("ParseException is expected due to the wrong key type");
    } catch (ParseException ex) {
        Assert.assertTrue(ex.getCause().getCause() instanceof UnresolvableKeyException);
    }
}
 
Example #2
Source File: KeyLocationResolverTest.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
@Test
public void testVerifyEcSignedTokenWithWrongAlgo() throws Exception {
    JwtClaimsBuilder builder = Jwt.claims("/Token1.json");
    builder.issuedAt(Instant.now().getEpochSecond());
    builder.expiresAt(Instant.now().getEpochSecond() + 300);
    String jwt = builder.sign(KeyUtils.readPrivateKey("/ecPrivateKey.pem", SignatureAlgorithm.ES256));
    JWTAuthContextInfoProvider provider = JWTAuthContextInfoProvider.createWithKeyLocation("publicKey.pem",
            "https://server.example.com");
    // default is RS256
    try {
        new DefaultJWTTokenParser().parse(jwt, provider.getContextInfo());
        Assert.fail("ParseException is expected due to the wrong expected algorithm");
    } catch (ParseException ex) {
        Assert.assertTrue(ex.getCause().getCause() instanceof InvalidAlgorithmException);
    }
}
 
Example #3
Source File: KeyLocationResolverKeyContentTest.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
private String readKeyContent(String keyLocation) throws Exception {
    InputStream is = KeyUtils.class.getResourceAsStream(keyLocation);
    StringWriter contents = new StringWriter();
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
        String line = null;
        while ((line = reader.readLine()) != null) {
            contents.write(line);
        }
    }
    return contents.toString();
}
 
Example #4
Source File: JwtClaimShortcutsTest.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
private static void verifyJwtWithArray(String jwt, String customClaim, String customValue) throws Exception {
    JsonWebSignature jws = new JsonWebSignature();
    jws.setKey(KeyUtils.readPublicKey("/publicKey.pem"));
    jws.setCompactSerialization(jwt);
    Assert.assertTrue(jws.verifySignature());
    JwtClaims claims = JwtClaims.parse(jws.getPayload());
    Assert.assertEquals(4, claims.getClaimsMap().size());
    @SuppressWarnings("unchecked")
    List<String> list = (List<String>) claims.getClaimValue(customClaim);
    Assert.assertEquals(1, list.size());
    Assert.assertEquals(customValue, list.get(0));
    Assert.assertNotNull(claims.getIssuedAt());
    Assert.assertNotNull(claims.getExpirationTime());
    Assert.assertNotNull(claims.getJwtId());
}
 
Example #5
Source File: JwtClaimShortcutsTest.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
private static void verifyJwtWithIssuer(String jwt) throws Exception {
    JsonWebSignature jws = new JsonWebSignature();
    jws.setKey(KeyUtils.readPublicKey("/publicKey.pem"));
    jws.setCompactSerialization(jwt);
    Assert.assertTrue(jws.verifySignature());
    JwtClaims claims = JwtClaims.parse(jws.getPayload());
    Assert.assertEquals(4, claims.getClaimsMap().size());
    Assert.assertEquals("iss", claims.getIssuer());
    Assert.assertNotNull(claims.getIssuedAt());
    Assert.assertNotNull(claims.getExpirationTime());
    Assert.assertNotNull(claims.getJwtId());
}
 
Example #6
Source File: JwtClaimShortcutsTest.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
private static void verifyJwt(String jwt, String customClaim, String customValue) throws Exception {
    JsonWebSignature jws = new JsonWebSignature();
    jws.setKey(KeyUtils.readPublicKey("/publicKey.pem"));
    jws.setCompactSerialization(jwt);
    Assert.assertTrue(jws.verifySignature());
    JwtClaims claims = JwtClaims.parse(jws.getPayload());
    Assert.assertEquals(4, claims.getClaimsMap().size());
    Assert.assertEquals(customValue, claims.getClaimValue(customClaim));
    Assert.assertNotNull(claims.getIssuedAt());
    Assert.assertNotNull(claims.getExpirationTime());
    Assert.assertNotNull(claims.getJwtId());
}
 
Example #7
Source File: PKSubUnitTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void testSubstitution() throws Exception {
    RSAPublicKey pk = (RSAPublicKey) KeyUtils.readPublicKey("/publicKey.pem");

    PublicKeySubstitution sub = new PublicKeySubstitution();
    PublicKeyProxy proxy = sub.serialize(pk);
    RSAPublicKey check = sub.deserialize(proxy);
    Assertions.assertEquals(pk, check);
}
 
Example #8
Source File: JwtEncryptionImpl.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public String encrypt(String keyLocation) throws JwtEncryptionException {
    Key key = null;
    try {
        key = KeyUtils.readEncryptionKey(keyLocation, (String) headers.get("kid"));
    } catch (Exception ex) {
        throw new JwtEncryptionException(ex);
    }
    return encryptInternal(key);
}
 
Example #9
Source File: JwtSignatureImpl.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
static Key getSigningKeyFromConfig(String kid) {
    String keyLocation = JwtBuildUtils.getConfigProperty("smallrye.jwt.sign.key-location", String.class);
    if (keyLocation != null) {
        try {
            return KeyUtils.readSigningKey(keyLocation, kid);
        } catch (Exception ex) {
            throw ImplMessages.msg.signingKeyCanNotBeLoadedFromLocation(keyLocation);
        }
    } else {
        throw ImplMessages.msg.signKeyLocationNotConfigured();
    }
}
 
Example #10
Source File: JwtSignatureImpl.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public String sign(String keyLocation) throws JwtSignatureException {
    Key key = null;
    try {
        key = KeyUtils.readSigningKey(keyLocation, (String) headers.get("kid"));
    } catch (Exception ex) {
        throw ImplMessages.msg.signatureException(ex);
    }
    return key instanceof PrivateKey ? sign((PrivateKey) key) : sign((SecretKey) key);

}
 
Example #11
Source File: KeyLocationResolver.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
static PublicKey tryAsPEMCertificate(String content) {
    PrincipalLogging.log.checkKeyContentIsBase64EncodedPEMCertificate();
    PublicKey key = null;
    try {
        key = KeyUtils.decodeCertificate(content);
        PrincipalLogging.log.publicKeyCreatedFromEncodedPEMCertificate();
    } catch (Exception e) {
        PrincipalLogging.log.keyContentIsNotValidEncodedPEMCertificate(e);
    }
    return key;
}
 
Example #12
Source File: KeyLocationResolver.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
static PublicKey tryAsPEMPublicKey(String content, SignatureAlgorithm algo) {
    PrincipalLogging.log.checkKeyContentIsBase64EncodedPEMKey();
    PublicKey key = null;
    try {
        key = KeyUtils.decodePublicKey(content, algo);
        PrincipalLogging.log.publicKeyCreatedFromEncodedPEMKey();
    } catch (Exception e) {
        PrincipalLogging.log.keyContentIsNotValidEncodedPEMKey(e);
    }
    return key;
}
 
Example #13
Source File: KeyLocationResolverTest.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
@Test
public void testVerifyEcSignedTokenWithEcKey() throws Exception {
    JwtClaimsBuilder builder = Jwt.claims("/Token1.json");
    builder.issuedAt(Instant.now().getEpochSecond());
    builder.expiresAt(Instant.now().getEpochSecond() + 300);
    String jwt = builder.sign(KeyUtils.readPrivateKey("/ecPrivateKey.pem", SignatureAlgorithm.ES256));
    JWTAuthContextInfoProvider provider = JWTAuthContextInfoProvider.createWithKeyLocation("ecPublicKey.pem",
            "https://server.example.com");
    JWTAuthContextInfo contextInfo = provider.getContextInfo();
    contextInfo.setSignatureAlgorithm(SignatureAlgorithm.ES256);
    Assert.assertNotNull(new DefaultJWTTokenParser().parse(jwt, contextInfo));
}
 
Example #14
Source File: DefaultJWTTokenParserTest.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
@Test
public void testParseJwtSignedWith1024RsaKeyLengthDisallowed() throws Throwable {
    KeyPair pair = KeyUtils.generateKeyPair(1024);
    String jwt = TokenUtils.generateTokenString(pair.getPrivate(), "kid", "/Token1.json", null, null);
    JWTAuthContextInfo context = new JWTAuthContextInfo((RSAPublicKey) pair.getPublic(), "https://server.example.com");
    ParseException thrown = assertThrows("InvalidJwtException is expected",
            ParseException.class, () -> parser.parse(jwt, context));
    assertTrue(thrown.getCause() instanceof InvalidJwtException);
}
 
Example #15
Source File: DefaultJWTTokenParserTest.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
@Test
public void testParseJwtSignedWith1024RsaKeyLengthAllowed() throws Exception {
    KeyPair pair = KeyUtils.generateKeyPair(1024);
    String jwt = TokenUtils.generateTokenString(pair.getPrivate(), "kid", "/Token1.json", null, null);
    JWTAuthContextInfo context = new JWTAuthContextInfo((RSAPublicKey) pair.getPublic(), "https://server.example.com");
    context.setRelaxVerificationKeyValidation(true);
    assertNotNull(parser.parse(jwt, context).getJwtClaims());
}
 
Example #16
Source File: KeyLocationResolverKeyContentTest.java    From smallrye-jwt with Apache License 2.0 4 votes vote down vote up
@Test
public void testVerifyWithPemKey() throws Exception {
    verifyToken(null, KeyUtils.removePemKeyBeginEnd(readKeyContent("/publicKey.pem")));
}
 
Example #17
Source File: TokenUtils.java    From thorntail with Apache License 2.0 4 votes vote down vote up
private static PrivateKey getPrivateKey() throws Exception {
    InputStream is = ContentTypesTest.class.getResourceAsStream("/keys/private-key.pem");
    return KeyUtils.decodePrivateKey(new String(IOUtil.asByteArray(is)));
}
 
Example #18
Source File: TokenUtils.java    From thorntail with Apache License 2.0 4 votes vote down vote up
private static PrivateKey getPrivateKey() throws Exception {
    InputStream is = TokenUtils.class.getResourceAsStream("/keys/private-key.pem");
    return KeyUtils.decodePrivateKey(new String(IOUtil.asByteArray(is)));
}
 
Example #19
Source File: JWTAuthContextInfoProvider.java    From thorntail with Apache License 2.0 4 votes vote down vote up
/**
 * Produce the JWTAuthContextInfo from a combination of the MP-JWT properties and the extended
 * fraction defined properties.
 * @return an Optional wrapper for the configured JWTAuthContextInfo
 */
@Produces
Optional<JWTAuthContextInfo> getOptionalContextInfo() {
    // Log the config values
    log.debugf("init, publicKeyPemEnc=%s, issuedBy=%s, expGracePeriodSecs=%d, jwksRefreshInterval=%d",
               publicKeyPemEnc.orElse("missing"), issuedBy, expGracePeriodSecs.get(), jwksRefreshInterval.get());

    /*
    FIXME Due to a bug in MP-Config (https://github.com/wildfly-extras/wildfly-microprofile-config/issues/43) we need to set all
    values to "NONE" as Optional Strings are populated with a ConfigProperty.defaultValue if they are absent. Fix this when MP-Config
    is repaired.
     */
    if (NONE.equals(publicKeyPemEnc.get()) && NONE.equals(jwksUri.get()) &&
            NONE.equals(super.getMpJwtPublicKey().get()) && NONE.equals(super.getMpJwtLocation().get())) {
        return Optional.empty();
    }
    log.warn("The use of all mpjwt.* properties is deprecated, use thorntail.microprofile.jwt.* properties instead");

    JWTAuthContextInfo contextInfo = new JWTAuthContextInfo();
    // Look to MP-JWT values first
    if (super.getMpJwtPublicKey().isPresent() && !NONE.equals(super.getMpJwtPublicKey().get())) {
        super.decodeMpJwtPublicKey(contextInfo);
    } else if (publicKeyPemEnc.isPresent() && !NONE.equals(publicKeyPemEnc.get())) {
        try {
            RSAPublicKey pk = (RSAPublicKey) KeyUtils.decodePublicKey(publicKeyPemEnc.get());
            contextInfo.setSignerKey(pk);
        } catch (Exception e) {
            throw new DeploymentException(e);
        }
    }

    String mpJwtIssuer = super.getMpJwtIssuer();
    if (mpJwtIssuer != null && !mpJwtIssuer.equals(NONE)) {
        contextInfo.setIssuedBy(mpJwtIssuer);
    } else if (issuedBy != null && !issuedBy.equals(NONE)) {
        contextInfo.setIssuedBy(issuedBy);
    }

    Optional<Boolean> mpJwtRequireIss = super.getMpJwtRequireIss();
    if (mpJwtRequireIss != null && mpJwtRequireIss.isPresent()) {
        contextInfo.setRequireIssuer(mpJwtRequireIss.get());
    } else {
        // Default is to require iss claim
        contextInfo.setRequireIssuer(true);
    }

    if (expGracePeriodSecs.isPresent()) {
        contextInfo.setExpGracePeriodSecs(expGracePeriodSecs.get());
    }
    // The MP-JWT location can be a PEM, JWK or JWKS
    Optional<String> mpJwtLocation = super.getMpJwtLocation();
    if (mpJwtLocation.isPresent() && !NONE.equals(mpJwtLocation.get())) {
        contextInfo.setPublicKeyLocation(super.getMpJwtLocation().get());
    } else if (jwksUri.isPresent() && !NONE.equals(jwksUri.get())) {
        contextInfo.setPublicKeyLocation(jwksUri.get());
    }
    if (jwksRefreshInterval.isPresent()) {
        contextInfo.setJwksRefreshInterval(jwksRefreshInterval.get());
    }

    if (super.getTokenHeader() != null) {
        contextInfo.setTokenHeader(super.getTokenHeader());
    }
    SmallryeJwtUtils.setContextTokenCookie(contextInfo, super.getTokenCookie());
    if (super.getDefaultGroupsClaim() != null && super.getDefaultGroupsClaim().isPresent()) {
        contextInfo.setDefaultGroupsClaim(super.getDefaultGroupsClaim().get());
    }

    return Optional.of(contextInfo);
}
 
Example #20
Source File: JwtSignEncryptTest.java    From smallrye-jwt with Apache License 2.0 4 votes vote down vote up
private static PublicKey getPublicKey() throws Exception {
    return KeyUtils.readPublicKey("/publicKey.pem");
}
 
Example #21
Source File: JwtSignEncryptTest.java    From smallrye-jwt with Apache License 2.0 4 votes vote down vote up
private static PrivateKey getPrivateKey() throws Exception {
    return KeyUtils.readPrivateKey("/privateKey.pem");
}
 
Example #22
Source File: JwtEncryptTest.java    From smallrye-jwt with Apache License 2.0 4 votes vote down vote up
private static PrivateKey getPrivateKey() throws Exception {
    return KeyUtils.readPrivateKey("/privateKey.pem");
}
 
Example #23
Source File: JwtSignTest.java    From smallrye-jwt with Apache License 2.0 4 votes vote down vote up
private static PublicKey getPublicKey() throws Exception {
    return KeyUtils.readPublicKey("/publicKey.pem");
}
 
Example #24
Source File: JwtSignTest.java    From smallrye-jwt with Apache License 2.0 4 votes vote down vote up
private static PrivateKey getPrivateKey() throws Exception {
    return KeyUtils.readPrivateKey("/privateKey.pem");
}
 
Example #25
Source File: KeyLocationResolverTest.java    From smallrye-jwt with Apache License 2.0 4 votes vote down vote up
public KeyLocationResolverTest() throws Exception {
    key = (RSAPublicKey) KeyUtils.generateKeyPair(2048).getPublic();
}