Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions jwt/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>io.scalecube</groupId>
<artifactId>scalecube-security-parent</artifactId>
<version>1.1.8-SNAPSHOT</version>
</parent>

<artifactId>scalecube-security-jwt</artifactId>
<name>${project.artifactId}</name>

<dependencies>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
</dependencies>

</project>
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package io.scalecube.security.tokens.jwt;
package io.scalecube.security.jwt;

import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.StringJoiner;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package io.scalecube.security.tokens.jwt;
package io.scalecube.security.jwt;

import java.util.ArrayList;
import java.util.List;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
package io.scalecube.security.tokens.jwt;
package io.scalecube.security.jwt;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import io.jsonwebtoken.JwsHeader;
import io.jsonwebtoken.LocatorAdapter;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
Expand All @@ -29,7 +27,11 @@
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

public class JwksKeyLocator extends LocatorAdapter<Key> {
/**
* Provides public keys from a remote JWKS endpoint and caches them temporarily. Keys are fetched on
* demand by their {@code kid} and automatically removed when expired.
*/
public class JwksKeyProvider {

private static final ObjectMapper OBJECT_MAPPER = newObjectMapper();

Expand All @@ -42,28 +44,38 @@ public class JwksKeyLocator extends LocatorAdapter<Key> {
private final Map<String, CachedKey> keyResolutions = new ConcurrentHashMap<>();
private final ReentrantLock cleanupLock = new ReentrantLock();

private JwksKeyLocator(Builder builder) {
private JwksKeyProvider(Builder builder) {
this.jwksUri = Objects.requireNonNull(builder.jwksUri, "jwksUri");
this.connectTimeout = Objects.requireNonNull(builder.connectTimeout, "connectTimeout");
this.requestTimeout = Objects.requireNonNull(builder.requestTimeout, "requestTimeout");
this.keyTtl = builder.keyTtl;
this.httpClient = HttpClient.newBuilder().connectTimeout(connectTimeout).build();
this.httpClient =
builder.httpClient != null
? builder.httpClient
: HttpClient.newBuilder().connectTimeout(connectTimeout).build();
}

public static Builder builder() {
return new Builder();
}

@Override
protected Key locate(JwsHeader header) {
/**
* Returns the public key for the given {@code kid}. If not cached, the key is fetched from the
* JWKS endpoint and cached for future use.
*
* @param kid key id of the public key to retrieve
* @return {@link Key} object associated with given {@code kid}
* @throws JwtUnavailableException if key cannot be found or JWKS cannot be retrieved
*/
public Key getKey(String kid) {
try {
return keyResolutions
.computeIfAbsent(
header.getKeyId(),
kid -> {
final var key = findKeyById(computeKeyList(), kid);
kid,
id -> {
final var key = findKeyById(computeKeyList(), id);
if (key == null) {
throw new JwtUnavailableException("Cannot find key by kid: " + kid);
throw new JwtUnavailableException("Cannot find key by kid: " + id);
}
return new CachedKey(key, System.currentTimeMillis() + keyTtl);
})
Expand Down Expand Up @@ -163,6 +175,7 @@ public static class Builder {
private Duration connectTimeout = Duration.ofSeconds(10);
private Duration requestTimeout = Duration.ofSeconds(10);
private int keyTtl = 60 * 1000;
private HttpClient httpClient;

private Builder() {}

Expand Down Expand Up @@ -214,8 +227,19 @@ public Builder keyTtl(int keyTtl) {
return this;
}

public JwksKeyLocator build() {
return new JwksKeyLocator(this);
/**
* Setter for optional {@link HttpClient}.
*
* @param httpClient httpClient
* @return this
*/
public Builder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}

public JwksKeyProvider build() {
return new JwksKeyProvider(this);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,29 +1,36 @@
package io.scalecube.security.tokens.jwt;
package io.scalecube.security.jwt;

import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.Locator;
import java.security.Key;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import java.security.interfaces.RSAPublicKey;
import java.util.concurrent.CompletableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JsonwebtokenResolver implements JwtTokenResolver {
/**
* Resolves and verifies JWT tokens using public keys provided by {@link JwksKeyProvider}. Tokens
* are validated asynchronously and parsed into {@link JwtToken} instances.
*/
public class JwksTokenResolver implements JwtTokenResolver {

private static final Logger LOGGER = LoggerFactory.getLogger(JsonwebtokenResolver.class);
private static final Logger LOGGER = LoggerFactory.getLogger(JwksTokenResolver.class);

private final JwtParser jwtParser;
private final JwksKeyProvider keyProvider;

public JsonwebtokenResolver(Locator<Key> keyLocator) {
jwtParser = Jwts.parser().keyLocator(keyLocator).build();
public JwksTokenResolver(JwksKeyProvider keyProvider) {
this.keyProvider = keyProvider;
}

@Override
public CompletableFuture<JwtToken> resolveToken(String token) {
return CompletableFuture.supplyAsync(
() -> {
final var claimsJws = jwtParser.parseSignedClaims(token);
return new JwtToken(claimsJws.getHeader(), claimsJws.getPayload());
final var rawToken = JWT.decode(token);
final var kid = rawToken.getKeyId();
final var publicKey = (RSAPublicKey) keyProvider.getKey(kid);
final var verifier = JWT.require(Algorithm.RSA256(publicKey, null)).build();
verifier.verify(token);
return JwtToken.parseToken(token);
})
.handle(
(jwtToken, ex) -> {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,24 @@
package io.scalecube.security.tokens.jwt;
package io.scalecube.security.jwt;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;

/**
* Represents parsed JWT (JSON Web Token), including its header and payload claims.
*
* @param header JWT header as map of key-value pairs
* @param payload JWT payload (claims) as map of key-value pairs
*/
public record JwtToken(Map<String, Object> header, Map<String, Object> payload) {

/**
* Parses given JWT without verifying its signature.
*
* @param token jwt token
* @return parsed token
* @return {@link JwtToken} object, or {@link JwtTokenException} will be thrown
*/
public static JwtToken parseToken(String token) {
String[] parts = token.split("\\.");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package io.scalecube.security.tokens.jwt;
package io.scalecube.security.jwt;

import java.util.StringJoiner;

Expand Down
19 changes: 19 additions & 0 deletions jwt/src/main/java/io/scalecube/security/jwt/JwtTokenResolver.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package io.scalecube.security.jwt;

import java.util.concurrent.CompletableFuture;

/**
* Resolves and verifies JWT tokens asynchronously. Implementations parse the token, validate its
* signature, and extract claims.
*/
public interface JwtTokenResolver {

/**
* Verifies given JWT and parses its header and claims.
*
* @param token jwt token
* @return async result completing with {@link JwtToken}, or completing exceptionally with {@link
* JwtTokenException} on failure
*/
CompletableFuture<JwtToken> resolveToken(String token);
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package io.scalecube.security.tokens.jwt;
package io.scalecube.security.jwt;

/**
* Special JWT exception type indicating transient error during token resolution. For example such
Expand Down
31 changes: 12 additions & 19 deletions pom.xml
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
Expand Down Expand Up @@ -33,7 +35,7 @@
</scm>

<modules>
<module>tokens</module>
<module>jwt</module>
<module>vault</module>
<module>tests</module>
</modules>
Expand All @@ -42,9 +44,10 @@
<vault-java-driver.version>5.1.0</vault-java-driver.version>
<jackson.version>2.19.2</jackson.version>
<slf4j.version>1.7.36</slf4j.version>
<jjwt.version>0.12.6</jjwt.version>
<auth0.java-jwt.version>4.5.0</auth0.java-jwt.version>

<mockito-junit.version>4.6.1</mockito-junit.version>
<mockito-junit.version>5.20.0</mockito-junit.version>
<mockito-inline.version>5.2.0</mockito-inline.version>
<junit-jupiter.version>5.8.2</junit-jupiter.version>
<hamcrest.version>1.3</hamcrest.version>
<log4j.version>2.17.2</log4j.version>
Expand All @@ -69,21 +72,11 @@
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- Jsonwebtoken -->
<!-- Auth0/JWT -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>${jjwt.version}</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>${jjwt.version}</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>${jjwt.version}</version>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>${auth0.java-jwt.version}</version>
</dependency>
<!-- Jackson -->
<dependency>
Expand Down Expand Up @@ -135,7 +128,7 @@
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>${mockito-junit.version}</version>
<version>${mockito-inline.version}</version>
<scope>test</scope>
</dependency>
<dependency>
Expand Down
2 changes: 1 addition & 1 deletion tests/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
<dependencies>
<dependency>
<groupId>io.scalecube</groupId>
<artifactId>scalecube-security-tokens</artifactId>
<artifactId>scalecube-security-jwt</artifactId>
<version>${project.parent.version}</version>
</dependency>
<dependency>
Expand Down
Loading