Java Code Examples for org.jose4j.jws.JsonWebSignature#setAlgorithmHeaderValue()

The following examples show how to use org.jose4j.jws.JsonWebSignature#setAlgorithmHeaderValue() . 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: JwtConsumerTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testNpeWithNonExtractableKeyDataHS256() throws Exception
{
    byte[] raw = Base64Url.decode("hup76LcA9B7pqrEtqyb4EBg6XCcr9r0iOCFF1FeZiJM");
    FakeHsmNonExtractableSecretKeySpec key = new FakeHsmNonExtractableSecretKeySpec(raw, "HmacSHA256");
    JwtClaims claims = new JwtClaims();
    claims.setExpirationTimeMinutesInTheFuture(5);
    claims.setSubject("subject");
    claims.setIssuer("issuer");
    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
    jws.setKey(key);
    String jwt = jws.getCompactSerialization();
    JwtConsumerBuilder jwtConsumerBuilder = new JwtConsumerBuilder();
    jwtConsumerBuilder.setAllowedClockSkewInSeconds(60);
    jwtConsumerBuilder.setRequireSubject();
    jwtConsumerBuilder.setExpectedIssuer("issuer");
    jwtConsumerBuilder.setVerificationKey(key);
    JwtConsumer jwtConsumer = jwtConsumerBuilder.build();
    JwtClaims processedClaims = jwtConsumer.processToClaims(jwt);
    System.out.println(processedClaims);
}
 
Example 2
Source File: JWTAuthPluginTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void beforeAll() throws Exception {
  JwtClaims claims = generateClaims();
  JsonWebSignature jws = new JsonWebSignature();
  jws.setPayload(claims.toJson());
  jws.setKey(rsaJsonWebKey.getPrivateKey());
  jws.setKeyIdHeaderValue(rsaJsonWebKey.getKeyId());
  jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);

  String testJwt = jws.getCompactSerialization();
  testHeader = "Bearer" + " " + testJwt;

  claims.unsetClaim("iss");
  claims.unsetClaim("aud");
  claims.unsetClaim("exp");
  jws.setPayload(claims.toJson());
  String slimJwt = jws.getCompactSerialization();
  slimHeader = "Bearer" + " " + slimJwt;
}
 
Example 3
Source File: JwtCachingAuthenticatorTest.java    From dropwizard-auth-jwt with Apache License 2.0 6 votes vote down vote up
private JwtContext tokenTwo() {
    final JwtClaims claims = new JwtClaims();
    claims.setSubject("good-guy-two");
    claims.setIssuer("Issuer");
    claims.setAudience("Audience");

    final JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA512);
    jws.setKey(new HmacKey(SECRET.getBytes(UTF_8)));
    jws.setDoKeyValidation(false);

    try {
        return consumer.process(jws.getCompactSerialization());
    }
    catch (Exception e) { throw Throwables.propagate(e); }
}
 
Example 4
Source File: TokenGenerator.java    From rufus with MIT License 6 votes vote down vote up
public String generateToken(String subject) {
    final JwtClaims claims = new JwtClaims();
    claims.setSubject(subject);
    claims.setExpirationTimeMinutesInTheFuture(TOKEN_EXPIRATION_IN_MINUTES);

    final JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setAlgorithmHeaderValue(HMAC_SHA256);
    jws.setKey(new HmacKey(tokenSecret));
    jws.setDoKeyValidation(false); //relaxes hmac key length restrictions

    try {
        return jws.getCompactSerialization();
    } catch (JoseException e) {
        throw new RuntimeException(e);
    }
}
 
Example 5
Source File: VerificationJwkSelectorTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Test
public void uniqueKidTestNriPhpJwksEndpoint() throws JoseException
{
    // JSON content from https://connect.openid4.us/connect4us.jwk on Jan 8, 2015
    String json = "{\n" +
            " \"keys\":[\n" +
            "  {\n" +
            "   \"kty\":\"RSA\",\n" +
            "   \"n\":\"tf_sB4M0sHearRLzz1q1JRgRdRnwk0lz-IcVDFlpp2dtDVyA-ZM8Tu1swp7upaTNykf7cp3Ne_6uW3JiKvRMDdNdvHWCzDHmbmZWGdnFF9Ve-D1cUxj4ETVpUM7AIXWbGs34fUNYl3Xzc4baSyvYbc3h6iz8AIdb_1bQLxJsHBi-ydg3NMJItgQJqBiwCmQYCOnJlekR-Ga2a5XlIx46Wsj3Pz0t0dzM8gVSU9fU3QrKKzDFCoFHTgig1YZNNW5W2H6QwANL5h-nbgre5sWmDmdnfiU6Pj5GOQDmp__rweinph8OAFNF6jVqrRZ3QJEmMnO42naWOsxV2FAUXafksQ\",\n" +
            "   \"e\":\"AQAB\",\n" +
            "   \"kid\":\"ABOP-00\"\n" +
            "  }\n" +
            " ]\n" +
            "}\n";

    JsonWebKeySet jwks = new JsonWebKeySet(json);

    VerificationJwkSelector verificationJwkSelector = new VerificationJwkSelector();
    JsonWebSignature jws = new JsonWebSignature();
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA384);
    jws.setKeyIdHeaderValue("ABOP-00");
    List<JsonWebKey> jsonWebKeys = jwks.getJsonWebKeys();
    List<JsonWebKey> selected = verificationJwkSelector.selectList(jws, jsonWebKeys);
    assertThat(1, equalTo(selected.size()));
    assertThat("ABOP-00", equalTo(selected.get(0).getKeyId()));
}
 
Example 6
Source File: BoxDeveloperEditionAPIConnection.java    From box-java-sdk with Apache License 2.0 5 votes vote down vote up
private String constructJWTAssertion(NumericDate now) {
    JwtClaims claims = new JwtClaims();
    claims.setIssuer(this.getClientID());
    claims.setAudience(JWT_AUDIENCE);
    if (now == null) {
        claims.setExpirationTimeMinutesInTheFuture(0.5f);
    } else {
        now.addSeconds(30L);
        claims.setExpirationTime(now);
    }
    claims.setSubject(this.entityID);
    claims.setClaim("box_sub_type", this.entityType.toString());
    claims.setGeneratedJwtId(64);

    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setKey(this.decryptPrivateKey());
    jws.setAlgorithmHeaderValue(this.getAlgorithmIdentifier());
    jws.setHeader("typ", "JWT");
    if ((this.publicKeyID != null) && !this.publicKeyID.isEmpty()) {
        jws.setHeader("kid", this.publicKeyID);
    }

    String assertion;

    try {
        assertion = jws.getCompactSerialization();
    } catch (JoseException e) {
        throw new BoxAPIException("Error serializing JSON Web Token assertion.", e);
    }

    return assertion;
}
 
Example 7
Source File: DefaultCipherExecutor.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Signs value based on the signing algorithm and the key length.
 *
 * @param value the value
 * @return the signed value
 */
private String signValue(@NotNull final String value) {
    try {
        final JsonWebSignature jws = new JsonWebSignature();
        jws.setPayload(value);
        jws.setAlgorithmHeaderValue(this.signingAlgorithm);
        jws.setKey(this.secretKeySigningKey);
        return jws.getCompactSerialization();
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 8
Source File: TokenUtils.java    From thorntail with Apache License 2.0 5 votes vote down vote up
public static String createTokenFromJson(String json) throws Exception {
    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(json);
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
    jws.setKey(getPrivateKey());
    return jws.getCompactSerialization();
}
 
Example 9
Source File: Token.java    From server_face_recognition with GNU General Public License v3.0 5 votes vote down vote up
public static Token cypherToken(String username, String password, int userId) {
    JwtClaims claims = new JwtClaims();
    claims.setIssuer("Sanstorik");
    claims.setAudience("User");
    claims.setExpirationTimeMinutesInTheFuture(60);
    claims.setGeneratedJwtId();
    claims.setIssuedAtToNow();
    claims.setNotBeforeMinutesInThePast(0.05f);
    claims.setSubject("neuralnetwork");

    claims.setClaim(USERNAME_KEY, username);
    claims.setClaim(PASSWORD_KEY, password);
    claims.setClaim(USERID_KEY, userId);


    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setKey(key.getPrivateKey());


    jws.setKeyIdHeaderValue(key.getKeyId());
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);

    Token token = null;
    try {
        token = new Token(jws.getCompactSerialization(),
                username, password, userId);
    } catch (JoseException e) {
        e.printStackTrace();
    }

    return token;
}
 
Example 10
Source File: KeyPairUtilTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void rsaPublicKeyEncodingDecodingAndSign() throws Exception
{
    PublicJsonWebKey publicJsonWebKey = ExampleRsaJwksFromJwe.APPENDIX_A_1;
    String pem = KeyPairUtil.pemEncode(publicJsonWebKey.getPublicKey());
    String expectedPem = "-----BEGIN PUBLIC KEY-----\r\n" +
            "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoahUIoWw0K0usKNuOR6H\r\n" +
            "4wkf4oBUXHTxRvgb48E+BVvxkeDNjbC4he8rUWcJoZmds2h7M70imEVhRU5djINX\r\n" +
            "tqllXI4DFqcI1DgjT9LewND8MW2Krf3Spsk/ZkoFnilakGygTwpZ3uesH+PFABNI\r\n" +
            "UYpOiN15dsQRkgr0vEhxN92i2asbOenSZeyaxziK72UwxrrKoExv6kc5twXTq4h+\r\n" +
            "QChLOln0/mtUZwfsRaMStPs6mS6XrgxnxbWhojf663tuEQueGC+FCMfra36C9knD\r\n" +
            "FGzKsNa7LZK2djYgyD3JR/MB/4NUJW/TqOQtwHYbxevoJArm+L5StowjzGy+/bq6\r\n" +
            "GwIDAQAB\r\n" +
            "-----END PUBLIC KEY-----";
    Assert.assertThat(pem, equalTo(expectedPem));


    RsaKeyUtil rsaKeyUtil = new RsaKeyUtil();
    PublicKey publicKey = rsaKeyUtil.fromPemEncoded(pem);
    Assert.assertThat(publicKey, equalTo(publicJsonWebKey.getPublicKey()));

    JwtClaims claims = new JwtClaims();
    claims.setSubject("meh");
    claims.setExpirationTimeMinutesInTheFuture(20);
    claims.setGeneratedJwtId();
    claims.setAudience("you");
    claims.setIssuer("me");
    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setKey(publicJsonWebKey.getPrivateKey());
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
    String jwt = jws.getCompactSerialization();

    Logger log = LoggerFactory.getLogger(this.getClass());
    log.debug("The following JWT and public key should be (and were on 11/11/15) usable and produce a valid " +
            "result at jwt.io (related to http://stackoverflow.com/questions/32744172):\n" + jwt + "\n" + pem);
}
 
Example 11
Source File: TokenUtils.java    From thorntail with Apache License 2.0 5 votes vote down vote up
public static String createToken(String groupName) throws Exception {
    JwtClaims claims = new JwtClaims();
    claims.setIssuer("http://testsuite-jwt-issuer.io");
    claims.setSubject(SUBJECT);
    claims.setStringListClaim("groups", groupName);
    claims.setClaim("upn", "[email protected]");
    claims.setExpirationTimeMinutesInTheFuture(1);

    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
    jws.setKey(getPrivateKey());
    return jws.getCompactSerialization();
}
 
Example 12
Source File: Http2ClientIT.java    From light-4j with Apache License 2.0 5 votes vote down vote up
public static String getJwt(JwtClaims claims) throws JoseException {
    String jwt;

    RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey(
            "/config/primary.jks", "password", "selfsigned");

    // A JWT is a JWS and/or a JWE with JSON claims as the payload.
    // In this example it is a JWS nested inside a JWE
    // So we first create a JsonWebSignature object.
    JsonWebSignature jws = new JsonWebSignature();

    // The payload of the JWS is JSON content of the JWT Claims
    jws.setPayload(claims.toJson());

    // The JWT is signed using the sender's private key
    jws.setKey(privateKey);
    jws.setKeyIdHeaderValue("100");

    // Set the signature algorithm on the JWT/JWS that will integrity protect the claims
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);

    // Sign the JWS and produce the compact serialization, which will be the inner JWT/JWS
    // representation, which is a string consisting of three dot ('.') separated
    // base64url-encoded parts in the form Header.Payload.Signature
    jwt = jws.getCompactSerialization();
    return jwt;
}
 
Example 13
Source File: TokenBuilder.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @return a download token with the current builder parameters.
 * @throws JoseException if there is an error generating the token
 */
public String getToken() throws JoseException {
    JwtClaims claims = getClaims();

    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
    jws.setKey(getKeyForSecret(
            this.secret.orElseThrow(
                () -> new IllegalArgumentException("No secret has been set"))));

    return jws.getCompactSerialization();
}
 
Example 14
Source File: Operation.java    From pingid-api-playground with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private String buildRequestToken(JSONObject requestBody) {
	
	JSONObject requestHeader = buildRequestHeader();
	
	JSONObject payload = new JSONObject();
	payload.put("reqHeader", requestHeader);
	payload.put("reqBody", requestBody);
	
	JsonWebSignature jws = new JsonWebSignature();

	jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
	jws.setHeader("orgAlias", this.orgAlias);
	jws.setHeader("token", this.token);
	
	jws.setPayload(payload.toJSONString());
	
    // Set the verification key
    HmacKey key = new HmacKey(Base64.decode(this.useBase64Key));
    jws.setKey(key);
	
	String jwsCompactSerialization = null;
	try {
		jwsCompactSerialization = jws.getCompactSerialization();
	} catch (JoseException e) {
		e.printStackTrace();
	}
	
	this.requestToken = jwsCompactSerialization;
			
	return jwsCompactSerialization;
}
 
Example 15
Source File: JwtHelper.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Builds a new access token.
 *
 * @param user the user (subject) to build the token, it will also add the roles as claims
 * @param clientId the client ID the token is for
 * @param scope the scope the token is valid for
 * @param tokenLifetime the lifetime of the token in minutes before it expires
 *
 * @return a base64-encoded signed JWT token to be passed as a bearer token in API requests
 */
public String getJwtAccessToken(User user, String clientId, String scope, int tokenLifetime) {
    try {
        JwtClaims jwtClaims = new JwtClaims();
        jwtClaims.setIssuer(ISSUER_NAME);
        jwtClaims.setAudience(AUDIENCE);
        jwtClaims.setExpirationTimeMinutesInTheFuture(tokenLifetime);
        jwtClaims.setGeneratedJwtId();
        jwtClaims.setIssuedAtToNow();
        jwtClaims.setNotBeforeMinutesInThePast(2);
        jwtClaims.setSubject(user.getName());
        jwtClaims.setClaim("client_id", clientId);
        jwtClaims.setClaim("scope", scope);
        jwtClaims.setStringListClaim("role",
                new ArrayList<>(user.getRoles() != null ? user.getRoles() : Collections.emptySet()));

        JsonWebSignature jws = new JsonWebSignature();
        jws.setPayload(jwtClaims.toJson());
        jws.setKey(jwtWebKey.getPrivateKey());
        jws.setKeyIdHeaderValue(jwtWebKey.getKeyId());
        jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
        String jwt = jws.getCompactSerialization();

        return jwt;
    } catch (Exception e) {
        logger.error("Error while writing JWT token", e);
        throw new RuntimeException(e.getMessage());
    }
}
 
Example 16
Source File: JWTVerificationkeyResolverTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public JsonWebSignature getJws() {
  JsonWebSignature jws = new JsonWebSignature();
  jws.setPayload(JWTAuthPluginTest.generateClaims().toJson());
  jws.setKey(getRsaKey().getPrivateKey());
  jws.setKeyIdHeaderValue(getRsaKey().getKeyId());
  jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
  return jws;
}
 
Example 17
Source File: JwtGenerator.java    From cloud-iot-core-androidthings with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting()
JwtGenerator(
        @NonNull KeyPair keyPair,
        @NonNull String jwtAudience,
        @NonNull Duration tokenLifetime,
        @NonNull Clock clock) {
    checkNotNull(keyPair, "keypair");
    checkNotNull(jwtAudience, "JWT audience");
    checkNotNull(tokenLifetime, "Token lifetime");
    checkNotNull(clock, "Clock");

    String algorithm = keyPair.getPrivate().getAlgorithm();
    if (!algorithm.equals(RSA_ALGORITHM) && !algorithm.equals(EC_ALGORITHM)) {
        throw new IllegalArgumentException("Keys use unsupported algorithm.");
    }

    mTokenLifetime = tokenLifetime;
    mClock = clock;

    mJws = new JsonWebSignature();
    mJws.setAlgorithmHeaderValue(algorithm.equals("RSA")
            ? AlgorithmIdentifiers.RSA_USING_SHA256
            : AlgorithmIdentifiers.ECDSA_USING_P256_CURVE_AND_SHA256);
    mJws.setHeader("typ", "JWT");
    mJws.setKey(keyPair.getPrivate());

    mClaims = new JwtClaims();
    mClaims.setAudience(jwtAudience);
}
 
Example 18
Source File: JwtConsumerTest.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
@Test
public void ctyRoundTrip() throws JoseException, InvalidJwtException, MalformedClaimException
{
    JsonWebKeySet jwks = new JsonWebKeySet("{\"keys\":[" +
            "{\"kty\":\"oct\",\"kid\":\"hk1\",\"alg\":\"HS256\",\"k\":\"RYCCH0Qai_7Clk_GnfBElTFIa5VJP3pJUDd8g5H0PKs\"}," +
            "{\"kty\":\"oct\",\"kid\":\"ek1\",\"alg\":\"A128KW\",\"k\":\"Qi38jqNMENlgKaVRbhKWnQ\"}]}");

    SimpleJwkFilter filter = new SimpleJwkFilter();
    filter.setKid("hk1", false);
    JsonWebKey hmacKey = filter.filter(jwks.getJsonWebKeys()).iterator().next();

    filter = new SimpleJwkFilter();
    filter.setKid("ek1", false);
    JsonWebKey encKey = filter.filter(jwks.getJsonWebKeys()).iterator().next();

    JwtClaims claims = new JwtClaims();
    claims.setSubject("subject");
    claims.setAudience("audience");
    claims.setIssuer("issuer");
    claims.setExpirationTimeMinutesInTheFuture(10);
    claims.setNotBeforeMinutesInThePast(5);
    claims.setGeneratedJwtId();

    JsonWebSignature jws = new JsonWebSignature();
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
    jws.setPayload(claims.toJson());
    jws.setKey(hmacKey.getKey());
    jws.setKeyIdHeaderValue(hmacKey.getKeyId());
    String innerJwt = jws.getCompactSerialization();

    JsonWebEncryption jwe = new JsonWebEncryption();
    jwe.setAlgorithmHeaderValue(KeyManagementAlgorithmIdentifiers.A128KW);
    jwe.setEncryptionMethodHeaderParameter(ContentEncryptionAlgorithmIdentifiers.AES_128_CBC_HMAC_SHA_256);
    jwe.setKey(encKey.getKey());
    jwe.setKeyIdHeaderValue(encKey.getKeyId());
    jwe.setContentTypeHeaderValue("JWT");
    jwe.setPayload(innerJwt);
    String jwt = jwe.getCompactSerialization();

    JwtConsumer jwtConsumer = new JwtConsumerBuilder()
            .setExpectedIssuer("issuer")
            .setExpectedAudience("audience")
            .setRequireSubject()
            .setRequireExpirationTime()
            .setDecryptionKey(encKey.getKey())
            .setVerificationKey(hmacKey.getKey())
            .build();

    JwtContext jwtContext = jwtConsumer.process(jwt);
    Assert.assertThat("subject", equalTo(jwtContext.getJwtClaims().getSubject()));
    List<JsonWebStructure> joseObjects = jwtContext.getJoseObjects();
    JsonWebStructure outerJsonWebObject = joseObjects.get(joseObjects.size() - 1);
    Assert.assertTrue(outerJsonWebObject instanceof JsonWebEncryption);
    Assert.assertThat("JWT", equalTo(outerJsonWebObject.getContentTypeHeaderValue()));
    Assert.assertThat("JWT", equalTo(outerJsonWebObject.getHeader(HeaderParameterNames.CONTENT_TYPE)));
    Assert.assertThat("JWT", equalTo(outerJsonWebObject.getHeaders().getStringHeaderValue(HeaderParameterNames.CONTENT_TYPE)));
    JsonWebStructure innerJsonWebObject = joseObjects.get(0);
    Assert.assertTrue(innerJsonWebObject instanceof JsonWebSignature);
}
 
Example 19
Source File: JwtVerifierTest.java    From light-4j with Apache License 2.0 4 votes vote down vote up
@Test
public void testVerifyJwtByJsonWebKeys() throws Exception {
    Map<String, Object> secretConfig = Config.getInstance().getJsonMapConfig(JwtIssuer.SECRET_CONFIG);
    JwtConfig jwtConfig = (JwtConfig) Config.getInstance().getJsonObjectConfig(JwtIssuer.JWT_CONFIG, JwtConfig.class);

    String fileName = jwtConfig.getKey().getFilename();
    String alias = jwtConfig.getKey().getKeyName();

    KeyStore ks = loadKeystore(fileName, (String)secretConfig.get(JwtIssuer.JWT_PRIVATE_KEY_PASSWORD));
    Key privateKey = ks.getKey(alias, ((String) secretConfig.get(JwtIssuer.JWT_PRIVATE_KEY_PASSWORD)).toCharArray());

    JsonWebSignature jws = new JsonWebSignature();

    String iss = "my.test.iss";
    JwtClaims jwtClaims = JwtClaims.parse("{\n" +
            "  \"sub\": \"5745ed4b-0158-45ff-89af-4ce99bc6f4de\",\n" +
            "  \"iss\": \"" + iss  +"\",\n" +
            "  \"subject_type\": \"client-id\",\n" +
            "  \"exp\": 1557419531,\n" +
            "  \"iat\": 1557419231,\n" +
            "  \"scope\": [\n" +
            "    \"my.test.scope.read\",\n" +
            "    \"my.test.scope.write\",\n" +
            "  ],\n" +
            "  \"consumer_application_id\": \"389\",\n" +
            "  \"request_transit\": \"63092\"\n" +
            "}");

    // The payload of the JWS is JSON content of the JWT Claims
    jws.setPayload(jwtClaims.toJson());

    // use private key to sign the JWT
    jws.setKey(privateKey);

    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);

    String jwt = jws.getCompactSerialization();

    Assert.assertNotNull(jwt);

    System.out.print("JWT = " + jwt);

    JwtVerifier jwtVerifier = new JwtVerifier(Config.getInstance().getJsonMapConfig(CONFIG_NAME));
    JwtClaims claims = jwtVerifier.verifyJwt(jwt, true, true, (kId, isToken) -> {
        try {
            // use public key to create the the JsonWebKey
            Key publicKey = ks.getCertificate(alias).getPublicKey();
            PublicJsonWebKey jwk = PublicJsonWebKey.Factory.newPublicJwk(publicKey);
            List<JsonWebKey> jwkList = Arrays.asList(jwk);
            return new JwksVerificationKeyResolver(jwkList);
        } catch (JoseException | KeyStoreException e) {
            throw new RuntimeException(e);
        }
    });

    Assert.assertNotNull(claims);
    Assert.assertEquals(iss, claims.getStringClaimValue("iss"));
}
 
Example 20
Source File: JWTAuthPluginIntegrationTest.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
@Before
public void setUp() throws Exception {
  super.setUp();
  
  configureCluster(NUM_SERVERS)// nodes
      .withSecurityJson(TEST_PATH().resolve("security").resolve("jwt_plugin_jwk_security.json"))
      .addConfig("conf1", TEST_PATH().resolve("configsets").resolve("cloud-minimal").resolve("conf"))
      .withDefaultClusterProperty("useLegacyReplicaAssignment", "false")
      .configure();
  baseUrl = cluster.getRandomJetty(random()).getBaseUrl().toString();

  String jwkJSON = "{\n" +
      "  \"kty\": \"RSA\",\n" +
      "  \"d\": \"i6pyv2z3o-MlYytWsOr3IE1olu2RXZBzjPRBNgWAP1TlLNaphHEvH5aHhe_CtBAastgFFMuP29CFhaL3_tGczkvWJkSveZQN2AHWHgRShKgoSVMspkhOt3Ghha4CvpnZ9BnQzVHnaBnHDTTTfVgXz7P1ZNBhQY4URG61DKIF-JSSClyh1xKuMoJX0lILXDYGGcjVTZL_hci4IXPPTpOJHV51-pxuO7WU5M9252UYoiYyCJ56ai8N49aKIMsqhdGuO4aWUwsGIW4oQpjtce5eEojCprYl-9rDhTwLAFoBtjy6LvkqlR2Ae5dKZYpStljBjK8PJrBvWZjXAEMDdQ8PuQ\",\n" +
      "  \"e\": \"AQAB\",\n" +
      "  \"use\": \"sig\",\n" +
      "  \"kid\": \"test\",\n" +
      "  \"alg\": \"RS256\",\n" +
      "  \"n\": \"jeyrvOaZrmKWjyNXt0myAc_pJ1hNt3aRupExJEx1ewPaL9J9HFgSCjMrYxCB1ETO1NDyZ3nSgjZis-jHHDqBxBjRdq_t1E2rkGFaYbxAyKt220Pwgme_SFTB9MXVrFQGkKyjmQeVmOmV6zM3KK8uMdKQJ4aoKmwBcF5Zg7EZdDcKOFgpgva1Jq-FlEsaJ2xrYDYo3KnGcOHIt9_0NQeLsqZbeWYLxYni7uROFncXYV5FhSJCeR4A_rrbwlaCydGxE0ToC_9HNYibUHlkJjqyUhAgORCbNS8JLCJH8NUi5sDdIawK9GTSyvsJXZ-QHqo4cMUuxWV5AJtaRGghuMUfqQ\"\n" +
      "}";

  PublicJsonWebKey jwk = RsaJsonWebKey.Factory.newPublicJwk(jwkJSON);
  JwtClaims claims = JWTAuthPluginTest.generateClaims();
  jws = new JsonWebSignature();
  jws.setPayload(claims.toJson());
  jws.setKey(jwk.getPrivateKey());
  jws.setKeyIdHeaderValue(jwk.getKeyId());
  jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);

  jwtTestToken = jws.getCompactSerialization();
  
  PublicJsonWebKey jwk2 = RsaJwkGenerator.generateJwk(2048);
  jwk2.setKeyId("k2");
  JsonWebSignature jws2 = new JsonWebSignature();
  jws2.setPayload(claims.toJson());
  jws2.setKey(jwk2.getPrivateKey());
  jws2.setKeyIdHeaderValue(jwk2.getKeyId());
  jws2.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
  jwtTokenWrongSignature = jws2.getCompactSerialization();

  cluster.waitForAllNodes(10);
}