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

The following examples show how to use org.jose4j.jws.JsonWebSignature#getCompactSerialization() . 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: 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 2
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 3
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 4
Source File: JWTokenFactory.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
private static String createToken(Key key, JsonObject jsonClaims) {

        JwtClaims claims = new JwtClaims();
        claims.setSubject(jsonClaims.toString());
        claims.setIssuedAtToNow();
        claims.setExpirationTime(NumericDate.fromSeconds(NumericDate.now().getValue() + JWT_TOKEN_EXPIRES_TIME));

        JsonWebSignature jws = new JsonWebSignature();
        jws.setDoKeyValidation(false);
        jws.setPayload(claims.toJson());
        jws.setKey(key);
        jws.setAlgorithmHeaderValue(ALG);

        try {
            return jws.getCompactSerialization();
        } catch (JoseException ex) {
            LOGGER.log(Level.SEVERE, null, ex);
        }

        return null;
    }
 
Example 5
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 6
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 7
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 8
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 9
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 10
Source File: DefaultCipherExecutor.java    From nano-framework with Apache License 2.0 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 11
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 12
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 13
Source File: JwtUtil.java    From light with Apache License 2.0 5 votes vote down vote up
public static String getJwt(Map<String, Object> userMap, Boolean rememberMe) throws JoseException {
    String jwt = null;
    JwtClaims claims = new JwtClaims();
    claims.setIssuer(issuer);
    claims.setAudience(audience);
    claims.setExpirationTimeMinutesInTheFuture(rememberMe ? rememberMin : expireMin);
    claims.setGeneratedJwtId();
    claims.setIssuedAtToNow();
    claims.setNotBeforeMinutesInThePast(clockSkewMin);
    claims.setSubject(subject);

    claims.setClaim("userId", userMap.get("userId"));
    claims.setClaim("clientId", userMap.get("clientId"));
    claims.setStringListClaim("roles", (List<String>)userMap.get("roles"));
    if(userMap.get("host") != null) claims.setClaim("host", userMap.get("host"));
    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);

    // 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();
    //System.out.println("JWT: " + jwt);

    return jwt;
}
 
Example 14
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 15
Source File: ExamplesTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void jwsSigningExample() throws JoseException
{
    //
    // An example of signing using JSON Web Signature (JWS)
    //

    // The content that will be signed
    String examplePayload = "This is some text that is to be signed.";

    // Create a new JsonWebSignature
    JsonWebSignature jws = new JsonWebSignature();

    // Set the payload, or signed content, on the JWS object
    jws.setPayload(examplePayload);

    // Set the signature algorithm on the JWS that will integrity protect the payload
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.ECDSA_USING_P256_CURVE_AND_SHA256);

    // Set the signing key on the JWS
    // Note that your application will need to determine where/how to get the key
    // and here we just use an example from the JWS spec
    PrivateKey privateKey = ExampleEcKeysFromJws.PRIVATE_256;
    jws.setKey(privateKey);

    // Sign the JWS and produce the compact serialization or complete JWS representation, which
    // is a string consisting of three dot ('.') separated base64url-encoded
    // parts in the form Header.Payload.Signature
    String jwsCompactSerialization = jws.getCompactSerialization();

    // Do something useful with your JWS
    System.out.println(jwsCompactSerialization);
}
 
Example 16
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 17
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;
}
 
Example 18
Source File: JwtHelperTest.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);

    JwtClaims claims = JwtHelper.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 19
Source File: SolrCloudAuthTestCase.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
static String getBearerAuthHeader(JsonWebSignature jws) throws JoseException {
  return "Bearer " + jws.getCompactSerialization();
}
 
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);
}