Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[improve][cli] Supports creating tokens with additional headers #22690

Merged
merged 4 commits into from
May 20, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Date;
import java.util.Map;
import java.util.Optional;
import javax.crypto.SecretKey;
import lombok.experimental.UtilityClass;
Expand Down Expand Up @@ -89,16 +90,22 @@ public static String encodeKeyBase64(Key key) {
return Encoders.BASE64.encode(key.getEncoded());
}

public static String createToken(Key signingKey, String subject, Optional<Date> expiryTime) {
public static String createToken(Key signingKey, String subject, Optional<Date> expiryTime,
Optional<Map<String, Object>> headers) {
JwtBuilder builder = Jwts.builder()
.setSubject(subject)
.signWith(signingKey);

expiryTime.ifPresent(builder::setExpiration);
headers.ifPresent(builder::setHeaderParams);

return builder.compact();
}

public static String createToken(Key signingKey, String subject, Optional<Date> expiryTime) {
return createToken(signingKey, subject, expiryTime, Optional.empty());
}

public static byte[] readKeyFromUrl(String keyConfUrl) throws IOException {
if (keyConfUrl.startsWith("data:") || keyConfUrl.startsWith("file:")) {
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import java.security.Key;
import java.security.KeyPair;
import java.util.Date;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.Callable;
import javax.crypto.SecretKey;
Expand Down Expand Up @@ -140,6 +141,11 @@ public static class CommandCreateToken implements Callable<Integer> {
description = "Pass the private key for signing the token. This can either be: data:, file:, etc..")
private String privateKey;

@Option(names = {"-h",
nodece marked this conversation as resolved.
Show resolved Hide resolved
"--headers"},
description = "Additional headers to token. Format: --headers key1=value1")
private Map<String, Object> headers;

@Override
public Integer call() throws Exception {
if (secretKey == null && privateKey == null) {
Expand All @@ -166,7 +172,7 @@ public Integer call() throws Exception {
? Optional.empty()
: Optional.of(new Date(System.currentTimeMillis() + expiryTime));

String token = AuthTokenUtils.createToken(signingKey, subject, optExpiryTime);
String token = AuthTokenUtils.createToken(signingKey, subject, optExpiryTime, Optional.ofNullable(headers));
System.out.println(token);

return 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,12 @@
*/
package org.apache.pulsar.utils.auth.tokens;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import io.jsonwebtoken.JwsHeader;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.lang.reflect.Field;
Expand All @@ -31,6 +36,37 @@
*/
public class TokensCliUtilsTest {

@Test
public void testCreateToken() {
PrintStream oldStream = System.out;
try {
ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
System.setOut(new PrintStream(baoStream));

new TokensCliUtils().execute(new String[]{"create-secret-key", "--base64"});
String secretKey = baoStream.toString();

baoStream.reset();

new TokensCliUtils().execute(new String[]{"create", "--secret-key", "data:;base64," + secretKey, "--subject", "test", "--headers", "kid=test"});
dao-jun marked this conversation as resolved.
Show resolved Hide resolved
String token = baoStream.toString();

Jwt<?, ?> jwt = Jwts.parserBuilder()
.setSigningKey(Decoders.BASE64.decode(secretKey))
.build()
Fixed Show fixed Hide fixed
.parse(token);

JwsHeader header = (JwsHeader) jwt.getHeader();
String keyId = header.getKeyId();
assertEquals(keyId, "test");

} catch (Exception e) {
throw new RuntimeException(e);
} finally {
System.setOut(oldStream);
}
}

/**
* Test tokens generate docs.
*
Expand Down