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

The following examples show how to use org.jose4j.jwt.JwtClaims#setGeneratedJwtId() . 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: JwtBuildUtils.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
static void setDefaultJwtClaims(JwtClaims claims) {

        long currentTimeInSecs = currentTimeInSecs();
        if (!claims.hasClaim(Claims.iat.name())) {
            claims.setIssuedAt(NumericDate.fromSeconds(currentTimeInSecs));
        }
        setExpiryClaim(claims);
        if (!claims.hasClaim(Claims.jti.name())) {
            claims.setGeneratedJwtId();
        }
        if (!claims.hasClaim(Claims.iss.name())) {
            String issuer = getConfigProperty("smallrye.jwt.new-token.issuer", String.class);
            if (issuer != null) {
                claims.setIssuer(issuer);
            }
        }
    }
 
Example 2
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 3
Source File: OauthHelperTest.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 4
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 5
Source File: JWTAuthPluginTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
protected static JwtClaims generateClaims() {
  JwtClaims claims = new JwtClaims();
  claims.setIssuer("IDServer");  // who creates the token and signs it
  claims.setAudience("Solr"); // to whom the token is intended to be sent
  claims.setExpirationTimeMinutesInTheFuture(10); // time when the token will expire (10 minutes from now)
  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.setSubject("solruser"); // the subject/principal is whom the token is about
  claims.setStringClaim("scope", "solr:read"); 
  claims.setClaim("name", "Solr User"); // additional claims/attributes about the subject can be added
  claims.setClaim("customPrincipal", "custom"); // additional claims/attributes about the subject can be added
  claims.setClaim("claim1", "foo"); // additional claims/attributes about the subject can be added
  claims.setClaim("claim2", "bar"); // additional claims/attributes about the subject can be added
  claims.setClaim("claim3", "foo"); // additional claims/attributes about the subject can be added
  List<String> roles = Arrays.asList("group-one", "other-group", "group-three");
  claims.setStringListClaim("roles", roles); // multi-valued claims work too and will end up as a JSON array
  return claims;
}
 
Example 6
Source File: TokenHelper.java    From git-as-svn with GNU General Public License v2.0 6 votes vote down vote up
@NotNull
public static String createToken(@NotNull JsonWebEncryption jwe, @NotNull User user, @NotNull NumericDate expireAt) {
  try {
    JwtClaims claims = new JwtClaims();
    claims.setExpirationTime(expireAt);
    claims.setGeneratedJwtId(); // a unique identifier for the token
    claims.setIssuedAtToNow();  // when the token was issued/created (now)
    claims.setNotBeforeMinutesInThePast(0.5f); // time before which the token is not yet valid (30 seconds ago)
    if (!user.isAnonymous()) {
      claims.setSubject(user.getUsername()); // the subject/principal is whom the token is about
      setClaim(claims, "email", user.getEmail());
      setClaim(claims, "name", user.getRealName());
      setClaim(claims, "external", user.getExternalId());
      setClaim(claims, "type", user.getType().name());
    }
    jwe.setPayload(claims.toJson());
    return jwe.getCompactSerialization();
  } catch (JoseException e) {
    throw new IllegalStateException(e);
  }
}
 
Example 7
Source File: TokenBuilder.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @return the current token JWT claims
 */
public JwtClaims getClaims() {
    JwtClaims claims = new JwtClaims();
    claims.setExpirationTimeMinutesInTheFuture(expirationTimeMinutesInTheFuture);
    claims.setIssuedAt(NumericDate.fromSeconds(issuedAt.getEpochSecond()));
    claims.setNotBeforeMinutesInThePast(NOT_BEFORE_MINUTES);
    claims.setGeneratedJwtId();
    return claims;
}
 
Example 8
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 9
Source File: JwtIssuer.java    From light-4j with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a default JwtClaims
 *
 * @return JwtClaims
 */
public static JwtClaims getDefaultJwtClaims() {

    JwtClaims claims = new JwtClaims();

    claims.setIssuer(jwtConfig.getIssuer());
    claims.setAudience(jwtConfig.getAudience());
    claims.setExpirationTimeMinutesInTheFuture(jwtConfig.getExpiredInMinutes());
    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", jwtConfig.getVersion());
    return claims;

}
 
Example 10
Source File: JwtIssuer.java    From light-4j with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a default JwtClaims
 * @param expiresIn expires in
 * @return JwtClaims
 */
public static JwtClaims getJwtClaimsWithExpiresIn(int expiresIn) {

    JwtClaims claims = new JwtClaims();

    claims.setIssuer(jwtConfig.getIssuer());
    claims.setAudience(jwtConfig.getAudience());
    claims.setExpirationTimeMinutesInTheFuture(expiresIn/60);
    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", jwtConfig.getVersion());
    return claims;
}
 
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: 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 13
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 14
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 15
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();
}
 
Example 16
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);
}