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

The following examples show how to use org.jose4j.jwt.JwtClaims#setStringListClaim() . 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: DefaultJWTTokenParser.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
private void mapRoles(JwtClaims claimsSet) {
    try {
        @SuppressWarnings("unchecked")
        Map<String, String> rolesMapping = claimsSet.getClaimValue(ROLE_MAPPINGS, Map.class);
        List<String> groups = claimsSet.getStringListClaimValue(Claims.groups.name());
        List<String> allGroups = new ArrayList<>(groups);
        for (Map.Entry<String, String> mapping : rolesMapping.entrySet()) {
            // If the key group is in groups list, add the mapped role
            if (groups.contains(mapping.getKey())) {
                allGroups.add(mapping.getValue());
            }
        }
        // Replace the groups with the original groups + mapped roles
        claimsSet.setStringListClaim(Claims.groups.name(), allGroups);
        PrincipalLogging.log.updatedGroups(allGroups);
    } catch (Exception e) {
        PrincipalLogging.log.failedToAccessRolesMappingClaim(e);
    }
}
 
Example 2
Source File: Oauth2TokenPostHandler.java    From light-oauth2 with Apache License 2.0 6 votes vote down vote up
private JwtClaims mockAcClaims(String clientId, String scopeString, String userId, String userType, String roles, String csrf, Map<String, Object> formMap) {
    JwtClaims claims = JwtIssuer.getDefaultJwtClaims();
    claims.setClaim("user_id", userId);
    claims.setClaim("user_type", userType);
    claims.setClaim("client_id", clientId);
    if(csrf != null) claims.setClaim("csrf", csrf);
    if(scopeString != null && scopeString.trim().length() > 0) {
        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(roles != null && roles.trim().length() > 0) {
        claims.setClaim("roles", roles);
    }

    if(formMap != null) {
        for(Map.Entry<String, Object> entry : formMap.entrySet()) {
            claims.setClaim(entry.getKey(), entry.getValue());
        }
    }
    return claims;
}
 
Example 3
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 4
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 5
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 6
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 7
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 8
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 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: 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 11
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 12
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 13
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 14
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 15
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;
}