import java.nio.file.*;
import java.security.cert.*;
import java.util.*;
import org.jose4j.jwa.AlgorithmConstraints;
import org.jose4j.jwk.*;
import org.jose4j.jws.*;
import org.jose4j.jwx.*;
public class OAuthIntrospectorVerifyTest {
  static boolean verify(String token, JsonWebKeySet ks) throws Exception {
    JsonWebStructure s = JsonWebStructure.fromCompactSerialization(token);
    System.out.println("class="+s.getClass()+" alg="+s.getAlgorithmHeaderValue()+" kid="+s.getKeyIdHeaderValue());
    if (!(s instanceof JsonWebSignature)) return false;
    JsonWebSignature j=(JsonWebSignature)s;
    System.out.println("keyType="+j.getKeyType());
    j.setAlgorithmConstraints(AlgorithmConstraints.NO_CONSTRAINTS);
    j.setDoKeyValidation(true);
    String kid=j.getKeyIdHeaderValue(); JsonWebKey k=null;
    if(kid!=null && !kid.isEmpty()) k=ks.findJsonWebKey(kid,j.getKeyType(),null,null);
    else if(!ks.getJsonWebKeys().isEmpty()) k=ks.getJsonWebKeys().get(0);
    System.out.println("selected="+(k==null?null:k.getKey()+" kty="+k.getKeyType()));
    if(k==null) return false;
    j.setKey(k.getKey());
    return j.verifySignature();
  }
  public static void main(String[] args) throws Exception {
    X509Certificate c=(X509Certificate)CertificateFactory.getInstance("X.509").generateCertificate(Files.newInputStream(Path.of(args[0])));
    JsonWebKey jwk=JsonWebKey.Factory.newJwk(c.getPublicKey()); jwk.setKeyId(c.getSerialNumber().toString());
    JsonWebKeySet ks=new JsonWebKeySet(List.of(jwk));
    for(int i=1;i<args.length;i++) { String t=Files.readString(Path.of(args[i])).trim(); System.out.println("==="+args[i]); try {System.out.println("verified="+verify(t,ks));} catch(Throwable e){e.printStackTrace(System.out);} }
  }
}
