似乎没有办法用标准库来处理这个问题。我找不到任何表明 JWK 中的自定义参数是合法的,但 Jose 库似乎只是忽略了它。所以我唯一能找到的就是“手动”阅读它。就像是:
import com.jayway.jsonpath.JsonPath;
import java.util.HashMap;
import java.util.List;
public class JWKSParserDirect {
private static final String jwks = "{\"keys\": [{" +
"\"kty\": \"RSA\"," +
"\"use\": \"sig\"," +
"\"alg\": \"RS256\"," +
"\"e\": \"AQAB\"," +
"\"kid\": \"2aktWjYabDofafVZIQc_452eAW9Z_pw7ULGGx87ufVA\"," +
"\"x5t\": \"5FTiZff07R_NuqNy5QXUK7uZNLo\"," +
"\"custom_field_1\": \"this is some content\"," +
"\"custom_field_2\": \"this is some content, too\"," +
"\"n\": \"foofoofoo\"," +
"\"x5c\": [\"blahblahblah\"]" +
"}" +
"," +
"{" +
"\"kty\": \"RSA\"," +
"\"use\": \"sig\"," +
"\"alg\": \"RS256\"," +
"\"e\": \"AQAB\"," +
"\"kid\": \"2aktWjYabDofafVZIQc_452eAW9Z_pw7ULGGx87ufVA\"," +
"\"x5t\": \"5FTiZff07R_NuqNy5QXUK7uZNLo\"," +
"\"custom_field_1\": \"this is some content the second time\"," +
"\"custom_field_2\": \"this is some content, too and two\"," +
"\"n\": \"foofoofoo\"," +
"\"x5c\": [\"blahblahblah\"]" +
"}]}";
@SuppressWarnings("unchecked")
public static void main(String[] argv) {
List<Object> keys = JsonPath.read(jwks, "$.keys[*]");
for (Object key : keys) {
HashMap<String, String> keyContents = (HashMap<String, String>) key;
System.out.println("custom_field_1 is \"" + keyContents.get("custom_field_1") + "\"");
System.out.println("custom_field_2 is \"" + keyContents.get("custom_field_2") + "\"");
}
}
}
或者,直接访问 JWK:
import com.jayway.jsonpath.JsonPath;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
public class JWKSParserURL {
@SuppressWarnings("unchecked")
public static void main(String[] argv) {
try {
URL url = new URL("https://someserver.tld/auth/realms/realmname/protocol/openid-connect/certs");
URLConnection urlConnection = url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
List<Object> keys = JsonPath.read(inputStream, "$.keys[*]");
for( Object key: keys) {
HashMap<String, String> keyContents = (HashMap<String, String>)key;
System.out.println("custom_field_1 is \"" + keyContents.get("custom_field_1") + "\"");
System.out.println("custom_field_2 is \"" + keyContents.get("custom_field_2") + "\"");
}
}
catch (IOException ioe) {
ioe.printStackTrace(System.err);
}
}
}
我无法找到 Json Path 键的正则表达式,因此您需要使用完整路径获取它们。你也可以有类似的东西:
List<String> customField1 = JsonPath.read(jwks, "$.key[*].custom_field_1");
获取“custom_field_1”值的列表。对我来说,这更加困难,因为您单独获取所有自定义字段值,而不是在每个键中。
同样,我在任何地方都找不到对自定义 JWK 字段的支持。 JW吨- 没问题,但不是 JWK。但是如果你有这个,我认为你需要在没有标准库的情况下提取这些字段。