com.nimbusds.jose.crypto.RSASSASigner Java Examples

The following examples show how to use com.nimbusds.jose.crypto.RSASSASigner. 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: JWSServiceTest.java    From graviteeio-access-management with Apache License 2.0 8 votes vote down vote up
@Test
public void testValidSignature_RSA() throws NoSuchAlgorithmException, JOSEException {
    //Generate RSA key
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(2048);
    KeyPair rsaKey = kpg.generateKeyPair();

    RSAPublicKey publicKey = (RSAPublicKey) rsaKey.getPublic();
    RSAKey key = new RSAKey();
    key.setKty("RSA");
    key.setKid(KID);
    key.setE(Base64.getUrlEncoder().encodeToString(publicKey.getPublicExponent().toByteArray()));
    key.setN(Base64.getUrlEncoder().encodeToString(publicKey.getModulus().toByteArray()));

    //Sign JWT with RSA algorithm
    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader.Builder(JWSAlgorithm.RS256).keyID(KID).build(),
            new JWTClaimsSet.Builder()
                    .expirationTime(Date.from(Instant.now().plus(1, ChronoUnit.DAYS)))
                    .build()
    );
    signedJWT.sign(new RSASSASigner((RSAPrivateKey) rsaKey.getPrivate()));

    assertTrue("Should be ok",jwsService.isValidSignature(signedJWT, key));
}
 
Example #2
Source File: CellerySignedJWTBuilder.java    From cellery-security with Apache License 2.0 6 votes vote down vote up
public String build() throws CelleryAuthException {

        // Build the JWT Header
        try {
            JWSHeader jwsHeader = buildJWSHeader();
            // Add mandatory claims
            addMandatoryClaims(claimSetBuilder);
            JWTClaimsSet claimsSet = this.claimSetBuilder.build();

            SignedJWT signedJWT = new SignedJWT(jwsHeader, claimsSet);
            JWSSigner signer = new RSASSASigner(getRSASigningKey());

            signedJWT.sign(signer);
            return signedJWT.serialize();
        } catch (IdentityOAuth2Exception | JOSEException e) {
            throw new CelleryAuthException("Error while generating the signed JWT.", e);
        }
    }
 
Example #3
Source File: Tokens.java    From tomee with Apache License 2.0 6 votes vote down vote up
public String asToken(final String claims) throws Exception {
    try {
        final JWSHeader header = new JWSHeader.Builder(new JWSAlgorithm("RS"+hashSize, Requirement.OPTIONAL))
                .type(JOSEObjectType.JWT)
                .build();

        final JWTClaimsSet claimsSet = JWTClaimsSet.parse(claims);

        final SignedJWT jwt = new SignedJWT(header, claimsSet);

        jwt.sign(new RSASSASigner(privateKey));

        return jwt.serialize();
    } catch (Exception e) {
        throw new RuntimeException("Could not sign JWT");
    }
}
 
Example #4
Source File: Tokens.java    From tomee with Apache License 2.0 6 votes vote down vote up
public static String asToken(final String claims) throws Exception {
    final PrivateKey pk = readPrivateKey("/testkey.pem");

    try {
        final JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256)
                .type(JOSEObjectType.JWT)
                .build();

        final JWTClaimsSet claimsSet = JWTClaimsSet.parse(claims);

        final SignedJWT jwt = new SignedJWT(header, claimsSet);

        jwt.sign(new RSASSASigner(pk));

        return jwt.serialize();
    } catch (Exception e) {
        throw new RuntimeException("Could not sign JWT");
    }
}
 
Example #5
Source File: Tokens.java    From tomee with Apache License 2.0 6 votes vote down vote up
public static String asToken(final String claims) throws Exception {
    final PrivateKey pk = readPrivateKey("/testkey.pem");

    try {
        final JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256)
                .type(JOSEObjectType.JWT)
                .build();

        final JWTClaimsSet claimsSet = JWTClaimsSet.parse(claims);

        final SignedJWT jwt = new SignedJWT(header, claimsSet);

        jwt.sign(new RSASSASigner(pk));

        return jwt.serialize();
    } catch (Exception e) {
        throw new RuntimeException("Could not sign JWT");
    }
}
 
Example #6
Source File: Tokens.java    From tomee with Apache License 2.0 6 votes vote down vote up
public static String asToken(final String claims) throws Exception {
    final PrivateKey pk = readPrivateKey("/testkey.pem");

    try {
        final JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256)
                .type(JOSEObjectType.JWT)
                .build();

        final JWTClaimsSet claimsSet = JWTClaimsSet.parse(claims);

        final SignedJWT jwt = new SignedJWT(header, claimsSet);

        jwt.sign(new RSASSASigner(pk));

        return jwt.serialize();
    } catch (Exception e) {
        throw new RuntimeException("Could not sign JWT");
    }
}
 
Example #7
Source File: JWTTokenTest.java    From knox with Apache License 2.0 6 votes vote down vote up
@Test
public void testTokenSignatureRS512() throws Exception {
  String[] claims = new String[4];
  claims[0] = "KNOXSSO";
  claims[1] = "[email protected]";
  claims[2] = "https://login.example.com";
  claims[3] = Long.toString( ( System.currentTimeMillis()/1000 ) + 300);
  JWT token = new JWTToken(JWSAlgorithm.RS512.getName(), claims);

  assertEquals("KNOXSSO", token.getIssuer());
  assertEquals("[email protected]", token.getSubject());
  assertEquals("https://login.example.com", token.getAudience());
  assertTrue(token.getHeader().contains(JWSAlgorithm.RS512.getName()));

  // Sign the token
  JWSSigner signer = new RSASSASigner(privateKey);
  token.sign(signer);
  assertTrue(token.getSignaturePayload().length > 0);

  // Verify the signature
  JWSVerifier verifier = new RSASSAVerifier(publicKey);
  assertTrue(token.verify(verifier));
}
 
Example #8
Source File: JWTTokenTest.java    From knox with Apache License 2.0 6 votes vote down vote up
@Test
public void testTokenSignature() throws Exception {
  String[] claims = new String[4];
  claims[0] = "KNOXSSO";
  claims[1] = "[email protected]";
  claims[2] = "https://login.example.com";
  claims[3] = Long.toString( ( System.currentTimeMillis()/1000 ) + 300);
  JWT token = new JWTToken("RS256", claims);

  assertEquals("KNOXSSO", token.getIssuer());
  assertEquals("[email protected]", token.getSubject());
  assertEquals("https://login.example.com", token.getAudience());

  // Sign the token
  JWSSigner signer = new RSASSASigner(privateKey);
  token.sign(signer);
  assertTrue(token.getSignaturePayload().length > 0);

  // Verify the signature
  JWSVerifier verifier = new RSASSAVerifier(publicKey);
  assertTrue(token.verify(verifier));
}
 
Example #9
Source File: AbstractJWTFilterTest.java    From knox with Apache License 2.0 6 votes vote down vote up
protected SignedJWT getJWT(String issuer, String sub, String aud, Date expires, Date nbf, RSAPrivateKey privateKey,
                           String signatureAlgorithm)
    throws Exception {
  List<String> audiences = new ArrayList<>();
  if (aud != null) {
    audiences.add(aud);
  }

  JWTClaimsSet claims = new JWTClaimsSet.Builder()
  .issuer(issuer)
  .subject(sub)
  .audience(aud)
  .expirationTime(expires)
  .notBeforeTime(nbf)
  .claim("scope", "openid")
  .build();

  JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.parse(signatureAlgorithm)).build();

  SignedJWT signedJWT = new SignedJWT(header, claims);
  JWSSigner signer = new RSASSASigner(privateKey);

  signedJWT.sign(signer);

  return signedJWT;
}
 
Example #10
Source File: TokenServiceResourceTest.java    From knox with Apache License 2.0 6 votes vote down vote up
@Override
public JWT issueToken(Principal p, List<String> audiences, String algorithm, long expires) {
  String[] claimArray = new String[4];
  claimArray[0] = "KNOXSSO";
  claimArray[1] = p.getName();
  claimArray[2] = null;
  if (expires == -1) {
    claimArray[3] = null;
  } else {
    claimArray[3] = String.valueOf(expires);
  }

  JWT token = new JWTToken(algorithm, claimArray, audiences);
  JWSSigner signer = new RSASSASigner(privateKey);
  token.sign(signer);

  return token;
}
 
Example #11
Source File: WebSSOResourceTest.java    From knox with Apache License 2.0 6 votes vote down vote up
@Override
public JWT issueToken(Principal p, List<String> audiences, String algorithm, long expires,
                      String signingKeystoreName, String signingKeystoreAlias, char[] signingKeystorePassphrase)
    throws TokenServiceException {
  String[] claimArray = new String[4];
  claimArray[0] = "KNOXSSO";
  claimArray[1] = p.getName();
  claimArray[2] = null;
  if (expires == -1) {
    claimArray[3] = null;
  } else {
    claimArray[3] = String.valueOf(expires);
  }

  JWT token = new JWTToken(algorithm, claimArray, audiences);
  RSAPrivateKey privateKey = getPrivateKey(signingKeystoreName, signingKeystoreAlias, signingKeystorePassphrase);
  JWSSigner signer = new RSASSASigner(privateKey);
  token.sign(signer);

  return token;
}
 
Example #12
Source File: JwtAuthorizerTest.java    From outbackcdx with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws Exception {
    RSAKey rsaJWK = new RSAKeyGenerator(2048).generate();
    RSAKey rsaPublicJWK = rsaJWK.toPublicJWK();
    JWSSigner signer = new RSASSASigner(rsaJWK);
    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
            .expirationTime(Date.from(Instant.now().plus(1, ChronoUnit.DAYS)))
            .claim("permissions", Arrays.asList(RULES_EDIT.toString(), INDEX_EDIT.toString()))
            .build();

    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader.Builder(JWSAlgorithm.RS256).keyID(rsaJWK.getKeyID()).build(),
            claimsSet);
    signedJWT.sign(signer);
    String token = signedJWT.serialize();

    JwtAuthorizer authorizer = new JwtAuthorizer(new ImmutableJWKSet<>(new JWKSet(rsaPublicJWK)), "permissions");
    Set<Permission> permissions = authorizer.verify("beARer " + token).permissions;
    assertEquals(EnumSet.of(RULES_EDIT, INDEX_EDIT), permissions);
}
 
Example #13
Source File: TestJWTAuthenticationHandler.java    From registry with Apache License 2.0 6 votes vote down vote up
protected SignedJWT getJWT(String sub, Date expires, RSAPrivateKey privateKey)
        throws Exception {
    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
            .subject(sub)
            .issueTime(new Date(new Date().getTime()))
            .issuer("https://c2id.com")
            .claim("scope", "openid")
            .audience("bar")
            .expirationTime(expires)
            .build();
    List<String> aud = new ArrayList<String>();
    aud.add("bar");

    JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).build();

    SignedJWT signedJWT = new SignedJWT(header, claimsSet);
    JWSSigner signer = new RSASSASigner(privateKey);

    signedJWT.sign(signer);

    return signedJWT;
}
 
Example #14
Source File: TokenUtil.java    From peer-os with Apache License 2.0 6 votes vote down vote up
public static String createTokenRSA( PrivateKey privateKey, String claimJson )
{
    try
    {
        JWSSigner signer = new RSASSASigner( ( RSAPrivateKey ) privateKey );

        Payload pl = new Payload( claimJson );
        JWSObject jwsObject = new JWSObject( new JWSHeader( JWSAlgorithm.RS256 ), pl );

        jwsObject.sign( signer );

        return jwsObject.serialize();
    }
    catch ( Exception e )
    {
        LOG.error( "Error creating RSA token", e.getMessage() );

        return "";
    }
}
 
Example #15
Source File: EncryptionUtility.java    From amex-api-java-client-core with Apache License 2.0 6 votes vote down vote up
public String sign(String algorithm, String kid, String keyStr, String dataToSign) {
    try {

        Key key = getKey(algorithm, keyStr);

        JWSHeader.Builder jwsBuilder = new JWSHeader.Builder("HS256".equals(algorithm) ? JWSAlgorithm.HS256 : JWSAlgorithm.RS256);
        jwsBuilder.keyID(kid);

        JWSHeader signingHeader = jwsBuilder.build();
        JWSSigner signer = "HS256".equals(algorithm) ? new MACSigner(key.getEncoded()) : new RSASSASigner((RSAPrivateKey) key);
        JWSObject jwsObject = new JWSObject(signingHeader, new Payload(dataToSign));
        jwsObject.sign(signer);
        checkObject(jwsObject);

        String parts[] = jwsObject.serialize().split("\\.");

        return "{\"protected\":\"" + parts[0] + "\", \"payload\":\"" + parts[1] + "\", \"signature\":\"" + parts[2] + "\"}";

    } catch (Exception e) {
        throw new CryptoException("Exception signing data: " + e.getMessage(), e);
    }
}
 
Example #16
Source File: AuthorizationRequestParseRequestObjectHandlerTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void override_redirect_uri() throws Exception {
    RSAKey rsaKey = getRSAKey();
    JWSSigner signer = new RSASSASigner(rsaKey);

    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
            .subject("alice")
            .issuer("https://c2id.com")
            .claim("redirect_uri", "https://op-test:60001/authz_cb")
            .expirationTime(new Date(new Date().getTime() + 60 * 1000))
            .build();

    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("rsa-signature").build(),
            claimsSet);

    signedJWT.sign(signer);

    String jwt = signedJWT.serialize();
    System.out.println(jwt);
}
 
Example #17
Source File: AuthorizationRequestParseRequestObjectHandlerTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void override_max_age() throws Exception {
    RSAKey rsaKey = getRSAKey();
    JWSSigner signer = new RSASSASigner(rsaKey);

    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
            .subject("alice")
            .issuer("https://c2id.com")
            .claim("max_age", 360000)
            .expirationTime(new Date(new Date().getTime() + 60 * 1000))
            .build();

    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("rsa-signature").build(),
            claimsSet);

    signedJWT.sign(signer);

    String jwt = signedJWT.serialize();
    System.out.println(jwt);
}
 
Example #18
Source File: JSONWebTokenManager.java    From authmore-framework with Apache License 2.0 6 votes vote down vote up
@Override
public TokenResponse create(ClientDetails client, String userId, Set<String> scopes) {
    assertValidateScopes(client, scopes);
    JWTClaimsSet claims = new JWTClaimsSet.Builder()
            .claim(TOKEN_USER_ID, userId)
            .claim(TOKEN_CLIENT_ID, client.getClientId())
            .claim(TOKEN_AUTHORITIES, client.getAuthoritySet())
            .claim(TOKEN_SCOPES, scopes)
            .claim(TOKEN_EXPIRE_AT, expireAtByLiveTime(client.getAccessTokenValiditySeconds()))
            .claim(TOKEN_RESOURCE_IDS, client.getResourceIds())
            .build();
    PrivateKey privateKey = keyPair.getPrivate();
    RSASSASigner signer = new RSASSASigner(privateKey);
    SignedJWT signedJWT = new SignedJWT(new JWSHeader.Builder(JWSAlgorithm.RS256).build(), claims);
    try {
        signedJWT.sign(signer);
    } catch (JOSEException e) {
        throw new OAuthException("Failed to sign jwt.");
    }
    return new TokenResponse(signedJWT.serialize(), client.getAccessTokenValiditySeconds(), scopes);
}
 
Example #19
Source File: AuthorizationRequestParseRequestObjectHandlerTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void invalid_do_not_override_state_and_nonce() throws Exception {
    RSAKey rsaKey = getRSAKey();
    JWSSigner signer = new RSASSASigner(rsaKey);

    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
            .subject("alice")
            .issuer("https://c2id.com")
            .claim("state", "override-state")
            .claim("nonce", "override-nonce")
            .expirationTime(new Date(new Date().getTime() + 60 * 1000))
            .build();

    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("rsa-signature").build(),
            claimsSet);

    signedJWT.sign(signer);

    String jwt = signedJWT.serialize();
    System.out.println(jwt);
}
 
Example #20
Source File: JwkKeyPairManager.java    From OAuth-2.0-Cookbook with MIT License 6 votes vote down vote up
public String getSignedContent(String content) {
    Payload contentPayload = new Payload(content);

    try {
        RSASSASigner rsa = new RSASSASigner((RSAPrivateKey) clientJwk);
        JWSAlgorithm alg = JWSAlgorithm.RS256;
        JWSHeader header = new JWSHeader.Builder(alg)
            .keyID(clientJwk.getKeyID())
            .build();
        JWSObject jws = new JWSObject(header, contentPayload);
        jws.sign(rsa);
        return jws.serialize();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #21
Source File: AuthorizationRequestParseRequestObjectHandlerTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void invalid_client() throws Exception {
    RSAKey rsaKey = getRSAKey();
    JWSSigner signer = new RSASSASigner(rsaKey);

    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
            .subject("alice")
            .issuer("https://c2id.com")
            .claim("client_id", "unknown_client")
            .expirationTime(new Date(new Date().getTime() + 60 * 1000))
            .build();

    System.out.println(new PlainJWT(claimsSet).serialize());
    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("rsa-signature").build(),
            claimsSet);

    signedJWT.sign(signer);

    String jwt = signedJWT.serialize();
    System.out.println(jwt);
}
 
Example #22
Source File: AuthorizationRequestParseRequestObjectHandlerTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void invalid_request_object() throws Exception {
    RSAKey rsaKey = getRSAKey();
    JWSSigner signer = new RSASSASigner(rsaKey);

    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
            .subject("alice")
            .issuer("https://c2id.com")
            .expirationTime(new Date(new Date().getTime() + 60 * 1000))
            .build();

    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("rsa-signature").build(),
            claimsSet);

    signedJWT.sign(signer);

    String jwt = signedJWT.serialize();
    System.out.println(jwt);
}
 
Example #23
Source File: DefaultTokenAuthorityService.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
public JWT issueToken(Principal p, List<String> audiences, String algorithm, long expires,
                      String signingKeystoreName, String signingKeystoreAlias, char[] signingKeystorePassphrase)
    throws TokenServiceException {
  String[] claimArray = new String[4];
  claimArray[0] = "KNOXSSO";
  claimArray[1] = p.getName();
  claimArray[2] = null;
  if (expires == -1) {
    claimArray[3] = null;
  }
  else {
    claimArray[3] = String.valueOf(expires);
  }

  JWT token;
  if (SUPPORTED_SIG_ALGS.contains(algorithm)) {
    token = new JWTToken(algorithm, claimArray, audiences);
    try {
      RSAPrivateKey key = getSigningKey(signingKeystoreName, signingKeystoreAlias, signingKeystorePassphrase);
      // allowWeakKey to not break existing 1024 bit certificates
      JWSSigner signer = new RSASSASigner(key, true);
      token.sign(signer);
    } catch (KeystoreServiceException e) {
      throw new TokenServiceException(e);
    }
  }
  else {
    throw new TokenServiceException("Cannot issue token - Unsupported algorithm");
  }

  return token;
}
 
Example #24
Source File: AuthorizationRequestParseRequestObjectHandlerTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void encrypted_request_object() throws Exception {
    RSAKey rsaKey = getRSAKey();
    JWSSigner signer = new RSASSASigner(rsaKey);

    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
            .subject("alice")
            .issuer("https://c2id.com")
            .claim("redirect_uri", "https://op-test:60001/authz_cb")
            .expirationTime(new Date(new Date().getTime() + 60 * 1000))
            .build();

    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("rsa-encryption").build(),
            claimsSet);

    signedJWT.sign(signer);

    // Create JWE object with signed JWT as payload
    JWEObject jweObject = new JWEObject(
            new JWEHeader.Builder(JWEAlgorithm.RSA_OAEP_256, EncryptionMethod.A256GCM)
                    .contentType("JWT") // required to indicate nested JWT
                    .build(),
            new Payload(signedJWT));

    // Encrypt with the recipient's public key
    jweObject.encrypt(new RSAEncrypter(rsaKey));

    String jwt = jweObject.serialize();
    System.out.println(jwt);
}
 
Example #25
Source File: DefaultTokenStateServiceTest.java    From knox with Apache License 2.0 5 votes vote down vote up
protected JWT getJWTToken(final long expiry) {
  String[] claims = new String[4];
  claims[0] = "KNOXSSO";
  claims[1] = "[email protected]";
  claims[2] = "https://login.example.com";
  if(expiry > 0) {
    claims[3] = Long.toString(expiry);
  }

  JWT token = new JWTToken("RS256", claims);
  // Sign the token
  JWSSigner signer = new RSASSASigner(privateKey);
  token.sign(signer);
  return token;
}
 
Example #26
Source File: TokenGenerator.java    From cruise-control with BSD 2-Clause "Simplified" License 5 votes vote down vote up
static TokenAndKeys generateToken(String subject, List<String> audience, long expirationTime) throws JOSEException {
  RSAKey rsaJwk = new RSAKeyGenerator(2048)
      .keyID("123")
      .generate();
  RSAKey rsaPublicJWK = rsaJwk.toPublicJWK();
  RSASSASigner signer = new RSASSASigner(rsaJwk);

  JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256)
      .type(JOSEObjectType.JWT)
      .build();
  JWTClaimsSet.Builder claimsSet = new JWTClaimsSet.Builder()
      .subject(subject)
      .issuer("https://linkedin.com");

  if (audience != null) {
    claimsSet.audience(audience);
  }

  if (expirationTime > 0) {
    claimsSet.expirationTime(new Date(expirationTime));
  } else {
    claimsSet.expirationTime(Date.from(Instant.now().plusSeconds(120)));
  }

  SignedJWT signedJWT = new SignedJWT(header, claimsSet.build());
  signedJWT.sign(signer);

  return new TokenAndKeys(signedJWT.serialize(), (RSAPrivateKey) signer.getPrivateKey(), rsaPublicJWK.toRSAPublicKey());
}
 
Example #27
Source File: JwtTokenGenerator.java    From microprofile1.4-samples with MIT License 5 votes vote down vote up
public static String generateJWTString(String jsonResource) throws Exception {
    byte[] byteBuffer = new byte[16384];
    currentThread().getContextClassLoader()
                   .getResource(jsonResource)
                   .openStream()
                   .read(byteBuffer);

    JSONParser parser = new JSONParser(DEFAULT_PERMISSIVE_MODE);
    JSONObject jwtJson = (JSONObject) parser.parse(byteBuffer);
    
    long currentTimeInSecs = (System.currentTimeMillis() / 1000);
    long expirationTime = currentTimeInSecs + 1000;
   
    jwtJson.put(Claims.iat.name(), currentTimeInSecs);
    jwtJson.put(Claims.auth_time.name(), currentTimeInSecs);
    jwtJson.put(Claims.exp.name(), expirationTime);
    
    SignedJWT signedJWT = new SignedJWT(new JWSHeader
                                        .Builder(RS256)
                                        .keyID("/privateKey.pem")
                                        .type(JWT)
                                        .build(), parse(jwtJson));
    
    signedJWT.sign(new RSASSASigner(readPrivateKey("privateKey.pem")));
    
    return signedJWT.serialize();
}
 
Example #28
Source File: CrossEncryptionTest.java    From oxAuth with MIT License 5 votes vote down vote up
@Test
public void nestedJWT() throws Exception {

    RSAKey senderJWK = (RSAKey) JWK.parse(senderJwkJson);

    RSAKey recipientPublicJWK = (RSAKey) (JWK.parse(recipientJwkJson));

    // Create JWT
    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader.Builder(JWSAlgorithm.RS256).keyID(senderJWK.getKeyID()).build(),
            new JWTClaimsSet.Builder()
                    .subject("testi")
                    .issuer("https:devgluu.saminet.local")
                    .build());

    signedJWT.sign(new RSASSASigner(senderJWK));

    JWEObject jweObject = new JWEObject(
            new JWEHeader.Builder(JWEAlgorithm.RSA_OAEP, EncryptionMethod.A128GCM)
                    .contentType("JWT") // required to indicate nested JWT
                    .build(),
            new Payload(signedJWT));

    // Encrypt with the recipient's public key
    RSAEncrypter encrypter = new RSAEncrypter(recipientPublicJWK);
    jweObject.encrypt(encrypter);

    final String jweString = jweObject.serialize();

    decryptAndValidateSignatureWithGluu(jweString);
}
 
Example #29
Source File: TokenUtils.java    From tomee with Apache License 2.0 5 votes vote down vote up
public static String generateJWTString(String jsonResource) throws Exception {
    byte[] byteBuffer = new byte[16384];
    currentThread().getContextClassLoader()
            .getResource(jsonResource)
            .openStream()
            .read(byteBuffer);

    JSONParser parser = new JSONParser(DEFAULT_PERMISSIVE_MODE);
    JSONObject jwtJson = (JSONObject) parser.parse(byteBuffer);

    long currentTimeInSecs = (System.currentTimeMillis() / 1000);
    long expirationTime = currentTimeInSecs + 1000;

    jwtJson.put(Claims.iat.name(), currentTimeInSecs);
    jwtJson.put(Claims.auth_time.name(), currentTimeInSecs);
    jwtJson.put(Claims.exp.name(), expirationTime);

    SignedJWT signedJWT = new SignedJWT(new JWSHeader
            .Builder(RS256)
            .keyID("/privateKey.pem")
            .type(JWT)
            .build(), parse(jwtJson));

    signedJWT.sign(new RSASSASigner(readPrivateKey("privateKey.pem")));

    return signedJWT.serialize();
}
 
Example #30
Source File: JWTUtils.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
public static JWToken issue(String subject, String keyId, PrivateKey privateKey, Long expires) throws JOSEException {

        JSONObject payload = new JSONObject();
        JWSHeader header = new JWSHeader(JWSAlgorithm.RS256, JOSEObjectType.JWT, null, null, null, null, null, null, null, null, keyId, null, null);
        payload.put("sub", subject);
        payload.put("exp", expires);
        JWSObject jwsObject = new JWSObject(header, new Payload(payload));
        jwsObject.sign(new RSASSASigner(privateKey));
        return new JWToken(jwsObject.serialize());
    }