Java Code Examples for org.jose4j.jwt.JwtClaims#setExpirationTimeMinutesInTheFuture()

The following examples show how to use org.jose4j.jwt.JwtClaims#setExpirationTimeMinutesInTheFuture() . 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: Http2ClientIT.java    From light-4j with Apache License 2.0 6 votes vote down vote up
private static JwtClaims getTestClaims() {
    JwtClaims claims = new JwtClaims();
    claims.setIssuer("urn:com:networknt:oauth2:v1");
    claims.setAudience("urn:com.networknt");
    claims.setExpirationTimeMinutesInTheFuture(10);
    claims.setGeneratedJwtId(); // a unique identifier for the token
    claims.setIssuedAtToNow();  // when the token was issued/created (now)
    claims.setNotBeforeMinutesInThePast(2); // time before which the token is not yet valid (2 minutes ago)
    claims.setClaim("version", "1.0");

    claims.setClaim("user_id", "steve");
    claims.setClaim("user_type", "EMPLOYEE");
    claims.setClaim("client_id", "aaaaaaaa-1234-1234-1234-bbbbbbbb");
    List<String> scope = Arrays.asList("api.r", "api.w");
    claims.setStringListClaim("scope", scope); // multi-valued claims work too and will end up as a JSON array
    return claims;
}
 
Example 2
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 3
Source File: JwtConsumerTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
private void littleJweRoundTrip(String alg, String enc, String b64uKey) throws Exception
{
    byte[] raw = Base64Url.decode(b64uKey);
    Key key = new FakeHsmNonExtractableSecretKeySpec(raw, "AES");
    JwtClaims claims = new JwtClaims();
    claims.setExpirationTimeMinutesInTheFuture(5);
    claims.setSubject("subject");
    claims.setIssuer("issuer");
    JsonWebEncryption jwe = new JsonWebEncryption();
    jwe.setPayload(claims.toJson());
    jwe.setAlgorithmHeaderValue(alg);
    jwe.setEncryptionMethodHeaderParameter(enc);
    jwe.setKey(key);

    String jwt = jwe.getCompactSerialization();
    JwtConsumerBuilder jwtConsumerBuilder = new JwtConsumerBuilder();
    jwtConsumerBuilder.setAllowedClockSkewInSeconds(60);
    jwtConsumerBuilder.setRequireSubject();
    jwtConsumerBuilder.setExpectedIssuer("issuer");
    jwtConsumerBuilder.setDecryptionKey(key);
    jwtConsumerBuilder.setDisableRequireSignature();
    JwtConsumer jwtConsumer = jwtConsumerBuilder.build();
    JwtClaims processedClaims = jwtConsumer.processToClaims(jwt);
    Assert.assertThat(processedClaims.getSubject(), equalTo("subject"));
}
 
Example 4
Source File: SecuredResource.java    From dropwizard-auth-jwt with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/generate-expired-token")
public Map<String, String> generateExpiredToken() {
    final JwtClaims claims = new JwtClaims();
    claims.setExpirationTimeMinutesInTheFuture(-20);
    claims.setSubject("good-guy");

    final JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setAlgorithmHeaderValue(HMAC_SHA256);
    jws.setKey(new HmacKey(tokenSecret));

    try {
        return singletonMap("token", jws.getCompactSerialization());
    }
    catch (JoseException e) { throw Throwables.propagate(e); }
}
 
Example 5
Source File: SecuredResource.java    From dropwizard-auth-jwt with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/generate-valid-token")
public Map<String, String> generateValidToken() {
    final JwtClaims claims = new JwtClaims();
    claims.setSubject("good-guy");
    claims.setExpirationTimeMinutesInTheFuture(30);

    final JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setAlgorithmHeaderValue(HMAC_SHA256);
    jws.setKey(new HmacKey(tokenSecret));

    try {
        return singletonMap("token", jws.getCompactSerialization());
    }
    catch (JoseException e) { throw Throwables.propagate(e); }
}
 
Example 6
Source File: Http2ClientTest.java    From light-4j with Apache License 2.0 6 votes vote down vote up
private static JwtClaims getTestClaims() {
    JwtClaims claims = new JwtClaims();
    claims.setIssuer("urn:com:networknt:oauth2:v1");
    claims.setAudience("urn:com.networknt");
    claims.setExpirationTimeMinutesInTheFuture(10);
    claims.setGeneratedJwtId(); // a unique identifier for the token
    claims.setIssuedAtToNow();  // when the token was issued/created (now)
    claims.setNotBeforeMinutesInThePast(2); // time before which the token is not yet valid (2 minutes ago)
    claims.setClaim("version", "1.0");

    claims.setClaim("user_id", "steve");
    claims.setClaim("user_type", "EMPLOYEE");
    claims.setClaim("client_id", "aaaaaaaa-1234-1234-1234-bbbbbbbb");
    List<String> scope = Arrays.asList("api.r", "api.w");
    claims.setStringListClaim("scope", scope); // multi-valued claims work too and will end up as a JSON array
    return claims;
}
 
Example 7
Source File: JwtIssuerTest.java    From light-4j with Apache License 2.0 5 votes vote down vote up
@Test
public void longlivedLightPortalLightapi() throws Exception {
    JwtClaims claims = ClaimsUtil.getTestClaims("[email protected]", "EMPLOYEE", "f7d42348-c647-4efb-a52d-4c5787421e72", Arrays.asList("portal.r", "portal.w"), "user lightapi.net admin");
    claims.setExpirationTimeMinutesInTheFuture(5256000);
    String jwt = JwtIssuer.getJwt(claims);
    System.out.println("***Long lived token for portal lightapi***: " + jwt);
}
 
Example 8
Source File: JwtIssuerTest.java    From light-4j with Apache License 2.0 5 votes vote down vote up
@Test
public void longlivedTokenizationJwt73() throws Exception {
    JwtClaims claims = ClaimsUtil.getTestClaims("steve", "EMPLOYEE", "f7d42348-c647-4efb-a52d-4c5787421e73", Arrays.asList("token.r", "token.w"), "user");
    claims.setExpirationTimeMinutesInTheFuture(5256000);
    String jwt = JwtIssuer.getJwt(claims);
    System.out.println("***Long lived token for tokenizaiton***: " + jwt);
}
 
Example 9
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 10
Source File: JwtIssuerTest.java    From light-4j with Apache License 2.0 5 votes vote down vote up
@Test
public void normalPetStoreJwt() throws Exception {
    JwtClaims claims = ClaimsUtil.getTestClaims("steve", "EMPLOYEE", "f7d42348-c647-4efb-a52d-4c5787421e72", Arrays.asList("write:pets", "read:pets"), "user");
    claims.setExpirationTimeMinutesInTheFuture(10);
    String jwt = JwtIssuer.getJwt(claims);
    System.out.println("***JWT***: " + jwt);
}
 
Example 11
Source File: JwtAuthProviderTest.java    From dropwizard-auth-jwt with Apache License 2.0 5 votes vote down vote up
private JwtClaims claimsForUser(String user) {
    final JwtClaims claims = new JwtClaims();
    claims.setExpirationTimeMinutesInTheFuture(5);
    claims.setSubject(user);
    claims.setIssuer("Issuer");
    claims.setAudience("Audience");
    return claims;
}
 
Example 12
Source File: JwtIssuerTest.java    From light-4j with Apache License 2.0 5 votes vote down vote up
@Test
public void longLivedCodegenJwt() throws Exception {
    JwtClaims claims = ClaimsUtil.getTestClaims("steve", "EMPLOYEE", "f7d42348-c647-4efb-a52d-4c5787421e72", Arrays.asList("codegen.r", "codegen.w", "server.info.r"), "user");
    claims.setExpirationTimeMinutesInTheFuture(5256000);
    String jwt = JwtIssuer.getJwt(claims);
    System.out.println("***LongLived Codegen JWT***: " + jwt);
}
 
Example 13
Source File: JwtIssuerTest.java    From light-4j with Apache License 2.0 5 votes vote down vote up
@Test
public void longLivedHelloWorldJwt() throws Exception {
    JwtClaims claims = ClaimsUtil.getTestClaims("steve", "EMPLOYEE", "f7d42348-c647-4efb-a52d-4c5787421e72", Arrays.asList("world.r", "world.w", "server.info.r"), "user");
    claims.setExpirationTimeMinutesInTheFuture(5256000);
    String jwt = JwtIssuer.getJwt(claims);
    System.out.println("***LongLived HelloWorld JWT***: " + jwt);
}
 
Example 14
Source File: JwtIssuerTest.java    From light-4j with Apache License 2.0 5 votes vote down vote up
@Test
public void longlivedLightPortalLocalhost() throws Exception {
    JwtClaims claims = ClaimsUtil.getTestClaims("[email protected]", "EMPLOYEE", "f7d42348-c647-4efb-a52d-4c5787421e73", Arrays.asList("portal.r", "portal.w"), "user lightapi.net admin");
    claims.setExpirationTimeMinutesInTheFuture(5256000);
    String jwt = JwtIssuer.getJwt(claims);
    System.out.println("***Long lived token for portal localhost***: " + jwt);
}
 
Example 15
Source File: TokenUtils.java    From thorntail with Apache License 2.0 5 votes vote down vote up
public static String createToken(String subject, String groupName) throws Exception {
    JwtClaims claims = new JwtClaims();
    claims.setIssuer("http://testsuite-jwt-issuer.io");
    claims.setSubject(subject);
    if (groupName != null) {
        claims.setStringListClaim("groups", groupName);
    }
    claims.setClaim("upn", "[email protected]");
    claims.setExpirationTimeMinutesInTheFuture(1);

    return createTokenFromJson(claims.toJson());
}
 
Example 16
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 17
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 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: PushService.java    From org.openhab.ui.habot with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Send a notification and wait for the response.
 *
 * @param notification
 * @return
 * @throws GeneralSecurityException
 * @throws IOException
 * @throws JoseException
 * @throws ExecutionException
 * @throws InterruptedException
 */
public Future<Response> send(Notification notification)
        throws GeneralSecurityException, IOException, JoseException, ExecutionException, InterruptedException {
    assert (verifyKeyPair());

    BaseEncoding base64url = BaseEncoding.base64Url();

    Encrypted encrypted = encrypt(notification.getPayload(), notification.getUserPublicKey(),
            notification.getUserAuth(), notification.getPadSize());

    byte[] dh = Utils.savePublicKey((ECPublicKey) encrypted.getPublicKey());
    byte[] salt = encrypted.getSalt();

    Invocation.Builder invocationBuilder = ClientBuilder.newClient().target(notification.getEndpoint()).request();
    MultivaluedMap<String, Object> headers = new MultivaluedHashMap<String, Object>();
    headers.add("TTL", String.valueOf(notification.getTTL()));

    if (notification.hasPayload()) {
        headers.add("Content-Type", "application/octet-stream");
        headers.add("Content-Encoding", "aesgcm");
        headers.add("Encryption", "salt=" + base64url.omitPadding().encode(salt));
        headers.add("Crypto-Key", "dh=" + base64url.encode(dh));
    }

    if (notification.isGcm()) {
        if (gcmApiKey == null) {
            throw new IllegalStateException(
                    "An GCM API key is needed to send a push notification to a GCM endpoint.");
        }

        headers.add("Authorization", "key=" + gcmApiKey);
    }

    if (vapidEnabled() && !notification.isGcm()) {
        JwtClaims claims = new JwtClaims();
        claims.setAudience(notification.getOrigin());
        claims.setExpirationTimeMinutesInTheFuture(12 * 60);
        claims.setSubject(subject);

        JsonWebSignature jws = new JsonWebSignature();
        jws.setHeader("typ", "JWT");
        jws.setHeader("alg", "ES256");
        jws.setPayload(claims.toJson());
        jws.setKey(privateKey);
        jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.ECDSA_USING_P256_CURVE_AND_SHA256);

        headers.add("Authorization", "WebPush " + jws.getCompactSerialization());

        byte[] pk = Utils.savePublicKey((ECPublicKey) publicKey);

        if (headers.containsKey("Crypto-Key")) {
            headers.putSingle("Crypto-Key",
                    headers.getFirst("Crypto-Key") + ";p256ecdsa=" + base64url.omitPadding().encode(pk));
        } else {
            headers.add("Crypto-Key", "p256ecdsa=" + base64url.encode(pk));
        }
    }

    invocationBuilder.headers(headers);

    if (notification.hasPayload()) {
        return invocationBuilder.async().post(Entity.entity(encrypted.getCiphertext(),
                new Variant(MediaType.APPLICATION_OCTET_STREAM_TYPE, (String) null, "aesgcm")));
    } else {
        return invocationBuilder.async().post(null);
    }
}
 
Example 20
Source File: TestUtils.java    From java with Apache License 2.0 4 votes vote down vote up
/**
 * Utility for generating JWTs
 *
 * @param uid Maps to the sub claim
 * @param issuer URL of the issuer
 * @param signing Private key to sign the JWT
 * @param dos Determines at what time point the JWT should be generated
 * @return
 * @throws Exception
 */
public static String generateJWT(String uid, String issuer, PrivateKey signing, DateOptions dos)
    throws Exception {
  JwtClaims claims = new JwtClaims();
  claims.setIssuer(issuer);
  ArrayList<String> audiences = new ArrayList<String>();

  claims.setSubject(uid);

  claims.setGeneratedJwtId();

  claims.setGeneratedJwtId(); // a unique identifier for the token

  if (dos == DateOptions.Now) {
    claims.setIssuedAtToNow(); // when the token was issued/created (now)
    claims.setNotBeforeMinutesInThePast(
        60000 / 1000 / 60); // time before which the token is not yet valid (2 minutes ago)
    claims.setExpirationTimeMinutesInTheFuture(
        60000 / 1000 / 60); // time before which the token is not yet valid (2 minutes ago)
  }

  if (dos == DateOptions.Past) {
    claims.setIssuedAt(NumericDate.fromMilliseconds(System.currentTimeMillis() - 120000L));
    claims.setNotBeforeMinutesInThePast(
        4); // time before which the token is not yet valid (2 minutes ago)
    claims.setExpirationTimeMinutesInTheFuture(
        -1); // time before which the token is not yet valid (2 minutes ago)
  }

  if (dos == DateOptions.Future) {
    claims.setIssuedAt(NumericDate.fromMilliseconds(System.currentTimeMillis() + 120000L));
    claims.setNotBeforeMinutesInThePast(
        -1); // time before which the token is not yet valid (2 minutes ago)
    claims.setExpirationTimeMinutesInTheFuture(
        4); // time before which the token is not yet valid (2 minutes ago)
  }

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

  jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
  return jws.getCompactSerialization();
}