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

The following examples show how to use org.jose4j.jws.JsonWebSignature#setKeyIdHeaderValue() . 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: 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 2
Source File: JsonWebToken.java    From datamill with ISC License 6 votes vote down vote up
public String encoded() {
    JsonWebSignature signature = new JsonWebSignature();

    signature.setPayload(claims.toJson());
    signature.setKeyIdHeaderValue(key.getId());

    switch (key.getType()) {
        case SYMMETRIC:
            signature.setKey(key.getKey());
            signature.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
            break;
        case RSA:
            signature.setKey(((JsonKeyPair) key).getPrivateKey());
            signature.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
            break;
    }

    try {
        return signature.getCompactSerialization();
    } catch (JoseException e) {
        throw new SecurityException(e);
    }
}
 
Example 3
Source File: Jose4jJoseImpl.java    From thorntail with Apache License 2.0 6 votes vote down vote up
@Override
public String sign(SignatureInput input) {
    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(input.getData());
    for (Map.Entry<String, Object> entry : input.getHeaders().entrySet()) {
        jws.getHeaders().setObjectHeaderValue(entry.getKey(), entry.getValue());
    }
    jws.setAlgorithmHeaderValue(config.signatureAlgorithm());
    if (!config.signatureDataEncoding()) {
        jws.getHeaders().setObjectHeaderValue(HeaderParameterNames.BASE64URL_ENCODE_PAYLOAD, false);
        jws.setCriticalHeaderNames(HeaderParameterNames.BASE64URL_ENCODE_PAYLOAD);
    }
    if (config.includeSignatureKeyAlias()) {
        jws.setKeyIdHeaderValue(signatureKeyAlias());
    }
    jws.setKey(getSignatureKey(jws, JoseOperation.SIGN));
    try {
        return config.signatureDataDetached()
                ? jws.getDetachedContentCompactSerialization() : jws.getCompactSerialization();
    } catch (org.jose4j.lang.JoseException ex) {
        throw new JoseException(ex.getMessage(), ex);
    }
}
 
Example 4
Source File: HttpsJwksVerificationKeyResolverTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testAnEx() throws Exception
{
    String location = "https://www.example.org/";

    Get mockGet = mock(Get.class);
    when(mockGet.get(location)).thenThrow(new IOException(location + "says 'no GET for you!'"));
    HttpsJwks httpsJkws = new HttpsJwks(location);
    httpsJkws.setSimpleHttpGet(mockGet);
    HttpsJwksVerificationKeyResolver resolver = new HttpsJwksVerificationKeyResolver(httpsJkws);

    JsonWebSignature jws = new JsonWebSignature();
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.ECDSA_USING_P256_CURVE_AND_SHA256);
    jws.setKeyIdHeaderValue("nope");
    try
    {
        Key key = resolver.resolveKey(jws, Collections.<JsonWebStructure>emptyList());
        fail("shouldn't have resolved a key but got " + key);

    }
    catch (UnresolvableKeyException e)
    {
        log.debug("this was expected and is okay: {}", e.toString());
    }
}
 
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: VerificationJwkSelectorTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Test
public void uniqueKidTestMiterJwksEndpoint() throws JoseException
{
    // JSON content from https://mitreid.org/jwk on Jan 8, 2015
    String json = "{\"keys\":[{\"alg\":\"RS256\",\"e\":\"AQAB\",\"n\":\"23zs5r8PQKpsKeoUd2Bjz3TJkUljWqMD8X98SaIb1LE7dCQzi9jwO58FGL0ieY1Dfnr9-g1iiY8sNzV-byawK98W9yFiopaghfoKtxXgUD8pi0fLPeWmAkntjn28Z_WZvvA265ELbBhphPXEJcFhdzUfgESHVuqFMEqp1pB-CP0\"," +
            "\"kty\":\"RSA\",\"kid\":\"rsa1\"}]}";

    JsonWebKeySet jwks = new JsonWebKeySet(json);

    VerificationJwkSelector verificationJwkSelector = new VerificationJwkSelector();
    JsonWebSignature jws = new JsonWebSignature();
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
    jws.setKeyIdHeaderValue("rsa1");
    List<JsonWebKey> jsonWebKeys = jwks.getJsonWebKeys();
    List<JsonWebKey> selected = verificationJwkSelector.selectList(jws, jsonWebKeys);
    assertThat(1, equalTo(selected.size()));
    assertThat("rsa1", equalTo(selected.get(0).getKeyId()));
}
 
Example 7
Source File: VerificationJwkSelectorTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Test
public void uniqueKidTestFRJwksEndpoint() throws JoseException
{
    // JSON content from https://demo.forgerock.com:8443/openam/oauth2/connect/jwk_uri on Jan 8, 2015
    String json = "{\"keys\":[{\"kty\":\"RSA\",\"kid\":\"fb301b61-9b8a-4c34-9212-5d6fb9df1a57\",\"use\":\"sig\",\"alg\":\"RS256\",\"n\":\"AK0kHP1O-RgdgLSoWxkuaYoi5Jic6hLKeuKw8WzCfsQ68ntBDf6tVOTn_kZA7Gjf4oJAL1dXLlxIEy-kZWnxT3FF-0MQ4WQYbGBfaW8LTM4uAOLLvYZ8SIVEXmxhJsSlvaiTWCbNFaOfiII8bhFp4551YB07NfpquUGEwOxOmci_\",\"e\":\"AQAB\"}]}";

    JsonWebKeySet jwks = new JsonWebKeySet(json);

    VerificationJwkSelector verificationJwkSelector = new VerificationJwkSelector();
    JsonWebSignature jws = new JsonWebSignature();
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
    jws.setKeyIdHeaderValue("fb301b61-9b8a-4c34-9212-5d6fb9df1a57");
    List<JsonWebKey> jsonWebKeys = jwks.getJsonWebKeys();
    List<JsonWebKey> selected = verificationJwkSelector.selectList(jws, jsonWebKeys);
    assertThat(1, equalTo(selected.size()));
    assertThat("fb301b61-9b8a-4c34-9212-5d6fb9df1a57", equalTo(selected.get(0).getKeyId()));
}
 
Example 8
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 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: Http2ClientTest.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 11
Source File: OauthHelperTest.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 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: JwtToken.java    From blueocean-plugin with MIT License 5 votes vote down vote up
/**
 * Generates base64 representation of JWT token sign using "RS256" algorithm
 *
 * getHeader().toBase64UrlEncode() + "." + getClaim().toBase64UrlEncode() + "." + sign
 *
 * @return base64 representation of JWT token
 */
public String sign() {
    for(JwtTokenDecorator decorator: JwtTokenDecorator.all()){
        decorator.decorate(this);
    }

    for(JwtSigningKeyProvider signer: JwtSigningKeyProvider.all()){
        SigningKey k = signer.select(this);
        if (k!=null) {
            try {
                JsonWebSignature jsonWebSignature = new JsonWebSignature();
                jsonWebSignature.setPayload(claim.toString());
                jsonWebSignature.setKey(k.getKey());
                jsonWebSignature.setKeyIdHeaderValue(k.getKid());
                jsonWebSignature.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
                jsonWebSignature.setHeader(HeaderParameterNames.TYPE, "JWT");

                return jsonWebSignature.getCompactSerialization();
            } catch (JoseException e) {
                String msg = "Failed to sign JWT token: " + e.getMessage();
                LOGGER.log(Level.SEVERE, "Failed to sign JWT token", e);
                throw new ServiceException.UnexpectedErrorException(msg, e);
            }
        }
    }

    throw new IllegalStateException("No key is available to sign a token");
}
 
Example 14
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 15
Source File: TokenUtils.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
/**
 * Utility method to generate a JWT string from a JSON resource file that is signed by the private key
 * using either RS256 or ES256 algorithm, possibly with invalid fields.
 *
 * @param pk - the private key to sign the token with
 * @param kid - the kid claim to assign to the token
 * @param jsonResName   - name of test resources file
 * @param invalidClaims - the set of claims that should be added with invalid values to test failure modes
 * @param timeClaims - used to return the exp, iat, auth_time claims
 * @return the JWT string
 * @throws Exception on parse failure
 */
public static String signClaims(PrivateKey pk, String kid, String jsonResName,
    Set<InvalidClaims> invalidClaims, Map<String, Long> timeClaims) throws Exception {

    if (invalidClaims == null) {
        invalidClaims = Collections.emptySet();
    }
    JwtClaims claims = createJwtClaims(jsonResName, invalidClaims, timeClaims);
    
    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    if (kid != null) {
        jws.setKeyIdHeaderValue(kid);
    }
    jws.setHeader("typ", "JWT");
    
    if (invalidClaims.contains(InvalidClaims.ALG)) {
        jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
        jws.setKey(KeyGenerator.getInstance("HMACSHA256").generateKey());
    }
    else {
        jws.setAlgorithmHeaderValue(pk instanceof RSAPrivateKey ? AlgorithmIdentifiers.RSA_USING_SHA256
            : AlgorithmIdentifiers.ECDSA_USING_P256_CURVE_AND_SHA256);
        if (invalidClaims.contains(InvalidClaims.SIGNER)) {
            // Generate a new random private key to sign with to test invalid signatures
            pk = generateKeyPair(2048).getPrivate();
        }
        jws.setKey(pk);   
    }
    return jws.getCompactSerialization();
}
 
Example 16
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);
}
 
Example 17
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 18
Source File: JwtIssuer.java    From light-4j with Apache License 2.0 4 votes vote down vote up
/**
 * A static method that generate JWT token from JWT claims object
 *
 * @param claims JwtClaims object
 * @return A string represents jwt token
 * @throws JoseException JoseException
 */
public static String getJwt(JwtClaims claims) throws JoseException {
    String jwt;
    RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey(
            jwtConfig.getKey().getFilename(), (String)secretConfig.get(JWT_PRIVATE_KEY_PASSWORD), jwtConfig.getKey().getKeyName());

    // 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);

    // Get provider from security config file, it should be two digit
    // And the provider id will set as prefix for keyid in the token header, for example: 05100
    // if there is no provider id, we use "00" for the default value
    String provider_id = "";
    if (jwtConfig.getProviderId() != null) {
        provider_id = jwtConfig.getProviderId();
        if (provider_id.length() == 1) {
            provider_id = "0" + provider_id;
        } else if (provider_id.length() > 2) {
            logger.error("provider_id defined in the security.yml file is invalid; the length should be 2");
            provider_id = provider_id.substring(0, 2);
        }
    }
    jws.setKeyIdHeaderValue(provider_id + jwtConfig.getKey().getKid());

    // 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;
}