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

The following examples show how to use org.jose4j.jwt.JwtClaims#setClaim() . 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: JwtAuthFilterTest.java    From trellis with Apache License 2.0 6 votes vote down vote up
@Test
void testJwtAuthWebidFilter() {
    final ContainerRequestContext mockContext = mock(ContainerRequestContext.class);
    assertNotNull(filter);
    assertNotNull(producer);

    final String webid = "https://people.apache.org/~acoburn/#i";
    final String iss = "https://example.com/idp/";
    final String sub = "acoburn";
    final JwtClaims claims = new JwtClaims();
    claims.setSubject(sub);
    claims.setIssuer(iss);
    claims.setClaim("webid", webid);

    producer.setJsonWebToken(new DefaultJWTCallerPrincipal(claims));
    assertDoesNotThrow(() -> filter.filter(mockContext));
    verify(mockContext).setSecurityContext(securityArgument.capture());
    assertEquals(webid, securityArgument.getValue().getUserPrincipal().getName());
}
 
Example 3
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 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: JwtGeneratorTest.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testJwtGen() throws Exception {
    JwtClaims claims = JwtIssuer.getDefaultJwtClaims();
    claims.setClaim("user_id", "steve");
    claims.setClaim("user_type", "EMPLOYEE");
    claims.setClaim("client_id", "ddcaf0ba-1131-2232-3313-d6f2753f25dc");
    claims.setClaim("csrf", Util.getUUID());
    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

    String jwt = JwtIssuer.getJwt(claims);
    Assert.assertNotNull(jwt);
    System.out.println(jwt);
}
 
Example 6
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 7
Source File: ClaimsUtil.java    From light-4j with Apache License 2.0 5 votes vote down vote up
public static JwtClaims getCustomClaims(String userId, String userType, String clientId, List<String> scope, Map<String, String> custom, String roles) {
    JwtClaims claims = JwtIssuer.getDefaultJwtClaims();
    claims.setClaim("user_id", userId);
    claims.setClaim("user_type", userType);
    claims.setClaim("client_id", clientId);
    claims.setClaim("roles", roles);
    custom.forEach((k, v) -> claims.setClaim(k, v));
    if(scope != null) claims.setStringListClaim("scope", scope); // multi-valued claims work too and will end up as a JSON array
    return claims;
}
 
Example 8
Source File: ClaimsUtil.java    From light-4j with Apache License 2.0 5 votes vote down vote up
public static JwtClaims getTestClaims(String userId, String userType, String clientId, List<String> scope, String roles) {
    JwtClaims claims = JwtIssuer.getDefaultJwtClaims();
    claims.setClaim("user_id", userId);
    claims.setClaim("user_type", userType);
    claims.setClaim("client_id", clientId);
    claims.setClaim("roles", roles);
    if(scope != null) claims.setStringListClaim("scope", scope); // multi-valued claims work too and will end up as a JSON array
    return claims;
}
 
Example 9
Source File: JwtMockHandler.java    From light-4j with Apache License 2.0 5 votes vote down vote up
public JwtClaims mockClaims() {
    JwtClaims claims = JwtIssuer.getDefaultJwtClaims();
    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 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: 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 12
Source File: Oauth2TokenPostHandler.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
private JwtClaims mockCcClaims(String clientId, String scopeString, Map<String, Object> formMap) {
    JwtClaims claims = JwtIssuer.getDefaultJwtClaims();
    claims.setClaim("client_id", clientId);
    List<String> scope = Arrays.asList(scopeString.split("\\s+"));
    claims.setStringListClaim("scope", scope); // multi-valued claims work too and will end up as a JSON array
    if(formMap != null) {
        for(Map.Entry<String, Object> entry : formMap.entrySet()) {
            claims.setClaim(entry.getKey(), entry.getValue());
        }
    }
    return claims;
}
 
Example 13
Source File: Oauth2SigningPostHandler.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
private JwtClaims mockCcClaims(String clientId, Integer expiresIn, Map<String, Object> formMap) {
    JwtClaims claims = JwtIssuer.getJwtClaimsWithExpiresIn(expiresIn);
    claims.setClaim("client_id", clientId);
    if(formMap != null) {
        for(Map.Entry<String, Object> entry : formMap.entrySet()) {
            claims.setClaim(entry.getKey(), entry.getValue());
        }
    }
    return claims;
}
 
Example 14
Source File: TokenUtils.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
private static JwtClaims createJwtClaims(String jsonResName, Set<InvalidClaims> invalidClaims,
        Map<String, Long> timeClaims) throws Exception {
    
    String content = readJsonContent(jsonResName);
    JwtClaims claims = JwtClaims.parse(content);

    // Change the issuer to INVALID_ISSUER for failure testing if requested
    if (invalidClaims.contains(InvalidClaims.ISSUER)) {
        claims.setIssuer("INVALID_ISSUER");
    }
    long currentTimeInSecs = currentTimeInSecs();
    long exp = currentTimeInSecs + 300;
    long iat = currentTimeInSecs;
    long authTime = currentTimeInSecs;
    boolean expWasInput = false;
    // Check for an input exp to override the default of now + 300 seconds
    if (timeClaims != null && timeClaims.containsKey(Claims.exp.name())) {
        exp = timeClaims.get(Claims.exp.name());
        expWasInput = true;
    }
    // iat and auth_time should be before any input exp value
    if (expWasInput) {
        iat = exp - 5;
        authTime = exp - 5;
    }
    claims.setIssuedAt(NumericDate.fromSeconds(iat));
    claims.setClaim(Claims.auth_time.name(), authTime);
    // If the exp claim is not updated, it will be an old value that should be seen as expired
    if (!invalidClaims.contains(InvalidClaims.EXP)) {
        claims.setExpirationTime(NumericDate.fromSeconds(exp));
    }
    // Return the token time values if requested
    if (timeClaims != null) {
        timeClaims.put(Claims.iat.name(), iat);
        timeClaims.put(Claims.auth_time.name(), authTime);
        timeClaims.put(Claims.exp.name(), exp);
    }
    return claims;
}
 
Example 15
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 16
Source File: OidcJsonWebTokenProducer.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private JsonWebToken getTokenCredential(Class<? extends TokenCredential> type) {
    if (identity.isAnonymous()) {
        return new NullJsonWebToken();
    }
    if (identity.getPrincipal() instanceof OidcJwtCallerPrincipal
            && ((OidcJwtCallerPrincipal) identity.getPrincipal()).getCredential().getClass() == type) {
        return (JsonWebToken) identity.getPrincipal();
    }
    TokenCredential credential = identity.getCredential(type);
    if (credential != null) {
        if (credential instanceof AccessTokenCredential && ((AccessTokenCredential) credential).isOpaque()) {
            throw new OIDCException("Opaque access token can not be converted to JsonWebToken");
        }
        JwtClaims jwtClaims;
        try {
            jwtClaims = new JwtConsumerBuilder()
                    .setSkipSignatureVerification()
                    .setSkipAllValidators()
                    .build().processToClaims(credential.getToken());
        } catch (InvalidJwtException e) {
            throw new OIDCException(e);
        }
        jwtClaims.setClaim(Claims.raw_token.name(), credential.getToken());
        return new OidcJwtCallerPrincipal(jwtClaims, credential);
    }
    String tokenType = type == AccessTokenCredential.class ? "access" : "ID";
    throw new OIDCException("Current identity is not associated with an " + tokenType + " token");
}
 
Example 17
Source File: DownloadTokenBuilder.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @return the current token JWT claims
 */
@Override
public JwtClaims getClaims() {
    JwtClaims claims = super.getClaims();
    claims.setClaim("org", this.orgId);
    onlyChannels.ifPresent(channels ->
            claims.setStringListClaim("onlyChannels",
                    channels.stream().collect(Collectors.toList())));
    return claims;
}
 
Example 18
Source File: JwtClaimsBuilderImpl.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
private static JwtClaims fromMapToJwtClaims(Map<String, Object> claimsMap) {
    JwtClaims claims = new JwtClaims();
    @SuppressWarnings("unchecked")
    Map<String, Object> newMap = (Map<String, Object>) prepareValue(claimsMap);
    for (Map.Entry<String, Object> entry : newMap.entrySet()) {
        claims.setClaim(entry.getKey(), entry.getValue());
    }
    return claims;
}
 
Example 19
Source File: TokenHelper.java    From git-as-svn with GNU General Public License v2.0 4 votes vote down vote up
private static void setClaim(JwtClaims claims, @NotNull String name, @Nullable Object value) {
  if (value != null) {
    claims.setClaim(name, value);
  }
}
 
Example 20
Source File: JWT_Encrypted_Creator_Callout.java    From iloveapis2015-jwt-jwe-jws with Apache License 2.0 4 votes vote down vote up
public ExecutionResult execute (MessageContext msgCtxt,
                                ExecutionContext exeCtxt) {

    String varName;
    try {
        //JWTClaimsSet claims = new JWTClaimsSet();
        JwtClaims claims = new JwtClaims();
        String ISSUER = getIssuer(msgCtxt);
        claims.setIssuer(ISSUER);
        Float expirationInMinutes = Float.valueOf(getExpirationInMinutes(msgCtxt));
        claims.setExpirationTimeMinutesInTheFuture(expirationInMinutes);
        String uniqueID = UUID.randomUUID().toString();
        claims.setJwtId(uniqueID);

        /***************************SENDER'S END ***********************************/
        claims.setSubject("users");
        claims.setClaim("email", "[email protected]");
        claims.setClaim("Country", "USA");
        claims.setClaim("active", "true");
        claims.setClaim("dealerId", "1234");
        claims.setClaim("url", "www.mycompany.com");

        RSAPublicKey publicKey = (RSAPublicKey) getPublicKey(msgCtxt);
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(256);
        SecretKey contentEncryptKey = keyGen.generateKey();

        JsonWebEncryption jwe = new JsonWebEncryption();
        jwe.setKey(publicKey);
        jwe.setPayload(claims.toJson());
        jwe.setAlgorithmHeaderValue(KeyManagementAlgorithmIdentifiers.RSA_OAEP_256);
        jwe.setContentEncryptionKey(contentEncryptKey.getEncoded());
        jwe.setEncryptionMethodHeaderParameter(ContentEncryptionAlgorithmIdentifiers.AES_128_CBC_HMAC_SHA_256);
        SecureRandom iv = SecureRandom.getInstance("SHA1PRNG");
        jwe.setIv(iv.generateSeed(16));
        String encryptedJwt = jwe.getCompactSerialization();
        System.out.println("Encrypted ::" + encryptedJwt);
        varName = getVarname("encryptedJwt");
        msgCtxt.setVariable(varName, encryptedJwt);
    }

    catch (Exception e) {
        //e.printStackTrace();
        varName = getVarname( "error");
        msgCtxt.setVariable(varName, "Exception (A): " + e.toString());
        System.out.println("exception: " + e.toString());
        varName = getVarname("stacktrace");
        msgCtxt.setVariable(varName, "Stack (A): " + ExceptionUtils.getStackTrace(e));
        return ExecutionResult.ABORT;
    }
    return ExecutionResult.SUCCESS;

}