org.jose4j.jwt.JwtClaims Java Examples

The following examples show how to use org.jose4j.jwt.JwtClaims. 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: 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 #2
Source File: JWTokenFactory.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
private static String createToken(Key key, JsonObject jsonClaims) {

        JwtClaims claims = new JwtClaims();
        claims.setSubject(jsonClaims.toString());
        claims.setIssuedAtToNow();
        claims.setExpirationTime(NumericDate.fromSeconds(NumericDate.now().getValue() + JWT_TOKEN_EXPIRES_TIME));

        JsonWebSignature jws = new JsonWebSignature();
        jws.setDoKeyValidation(false);
        jws.setPayload(claims.toJson());
        jws.setKey(key);
        jws.setAlgorithmHeaderValue(ALG);

        try {
            return jws.getCompactSerialization();
        } catch (JoseException ex) {
            LOGGER.log(Level.SEVERE, null, ex);
        }

        return null;
    }
 
Example #3
Source File: TokenUtils.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
/**
 * Utility method to generate a JWT string from a JSON resource file that is encrypted by the public key,
 * possibly with invalid fields.
 *
 * @param pk - the public key to encrypt the token with
 * @param kid - the kid header to assign to the token
 * @param jsonResName   - name of test resources file
 * @param invalidClaims - the set of claims that should be added with invalid values to test failure modes
 * @param timeClaims - used to return the exp, iat, auth_time claims
 * @return the JWT string
 * @throws Exception on parse failure
 */
public static String encryptClaims(PublicKey pk, String kid, String jsonResName, Set<InvalidClaims> invalidClaims,
        Map<String, Long> timeClaims) throws Exception {
    if (invalidClaims == null) {
        invalidClaims = Collections.emptySet();
    }
    JwtClaims claims = createJwtClaims(jsonResName, invalidClaims, timeClaims);

    Key key = null;
    if (invalidClaims.contains(InvalidClaims.ENCRYPTOR)) {
        // Generate a new random private key to sign with to test invalid signatures
        KeyPair keyPair = generateKeyPair(2048);
        key = keyPair.getPublic();
    }
    else if (invalidClaims.contains(InvalidClaims.ALG)) {
        key = KeyGenerator.getInstance("AES").generateKey();
    }
    else {
        key = pk;
    }
    
    return encryptString(key, kid, claims.toJson(), false);
}
 
Example #4
Source File: DefaultJWTTokenParser.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
private void verifyTimeToLive(JWTAuthContextInfo authContextInfo, JwtClaims claimsSet) throws ParseException {
    final Long maxTimeToLiveSecs = authContextInfo.getMaxTimeToLiveSecs();

    if (maxTimeToLiveSecs != null) {
        final NumericDate iat;
        final NumericDate exp;

        try {
            iat = claimsSet.getIssuedAt();
            exp = claimsSet.getExpirationTime();
        } catch (Exception e) {
            throw PrincipalMessages.msg.failedToVerifyMaxTTL(e);
        }

        if (exp.getValue() - iat.getValue() > maxTimeToLiveSecs) {
            throw PrincipalMessages.msg.expExceeded(exp, maxTimeToLiveSecs, iat);
        }
    } else {
        PrincipalLogging.log.noMaxTTLSpecified();
    }
}
 
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: JWTokenFactory.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
public static String validateSharedResourceToken(Key key, String jwt) {

        JwtConsumer jwtConsumer = new JwtConsumerBuilder()
                .setVerificationKey(key)
                .setRelaxVerificationKeyValidation()
                .build();

        try {
            JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt);
            String subject = jwtClaims.getSubject();
            try (JsonReader reader = Json.createReader(new StringReader(subject))) {
                JsonObject subjectObject = reader.readObject(); // JsonParsingException
                return subjectObject.getString(SHARED_ENTITY_UUID); // Npe
            }
        } catch (InvalidJwtException | MalformedClaimException | JsonParsingException | NullPointerException e) {
            LOGGER.log(Level.FINE, "Cannot validate jwt token", e);
        }

        return null;

    }
 
Example #7
Source File: JwtConsumerTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testNpeWithNonExtractableKeyDataHS256() throws Exception
{
    byte[] raw = Base64Url.decode("hup76LcA9B7pqrEtqyb4EBg6XCcr9r0iOCFF1FeZiJM");
    FakeHsmNonExtractableSecretKeySpec key = new FakeHsmNonExtractableSecretKeySpec(raw, "HmacSHA256");
    JwtClaims claims = new JwtClaims();
    claims.setExpirationTimeMinutesInTheFuture(5);
    claims.setSubject("subject");
    claims.setIssuer("issuer");
    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
    jws.setKey(key);
    String jwt = jws.getCompactSerialization();
    JwtConsumerBuilder jwtConsumerBuilder = new JwtConsumerBuilder();
    jwtConsumerBuilder.setAllowedClockSkewInSeconds(60);
    jwtConsumerBuilder.setRequireSubject();
    jwtConsumerBuilder.setExpectedIssuer("issuer");
    jwtConsumerBuilder.setVerificationKey(key);
    JwtConsumer jwtConsumer = jwtConsumerBuilder.build();
    JwtClaims processedClaims = jwtConsumer.processToClaims(jwt);
    System.out.println(processedClaims);
}
 
Example #8
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 #9
Source File: BoxDeveloperEditionAPIConnectionTest.java    From box-java-sdk with Apache License 2.0 6 votes vote down vote up
private JwtClaims getClaimsFromRequest(Request request) throws Exception {

        // Get the JWT out of the request body
        String body = request.getBodyAsString();
        String[] tokens = body.split("&");
        String jwt = null;
        for (String s : tokens) {
            String[] parts = s.split("=");
            if (parts[0] != null && parts[0].equals("assertion") && parts[1] != null) {
                jwt = parts[1];
            }
        }
        if (jwt == null) {
            throw new Exception("No jwt assertion found in request body");
        }

        // Parse out the JWT to verify the claims
        JwtConsumer jwtConsumer = new JwtConsumerBuilder()
                .setSkipSignatureVerification()
                .setSkipAllValidators()
                .build();
        return jwtConsumer.processToClaims(jwt);
    }
 
Example #10
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 #11
Source File: JwtAuthFilterTest.java    From trellis with Apache License 2.0 6 votes vote down vote up
@Test
void testJwtAuthFilter() {
    final ContainerRequestContext mockContext = mock(ContainerRequestContext.class);
    assertNotNull(filter);
    assertNotNull(producer);

    final String iss = "https://example.com/idp/";
    final String sub = "acoburn";
    final JwtClaims claims = new JwtClaims();
    claims.setSubject(sub);
    claims.setIssuer(iss);

    producer.setJsonWebToken(new DefaultJWTCallerPrincipal(claims));
    assertDoesNotThrow(() -> filter.filter(mockContext));
    verify(mockContext).setSecurityContext(securityArgument.capture());
    assertEquals(iss + sub, securityArgument.getValue().getUserPrincipal().getName());
}
 
Example #12
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 #13
Source File: JWTAuthPluginTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void beforeAll() throws Exception {
  JwtClaims claims = generateClaims();
  JsonWebSignature jws = new JsonWebSignature();
  jws.setPayload(claims.toJson());
  jws.setKey(rsaJsonWebKey.getPrivateKey());
  jws.setKeyIdHeaderValue(rsaJsonWebKey.getKeyId());
  jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);

  String testJwt = jws.getCompactSerialization();
  testHeader = "Bearer" + " " + testJwt;

  claims.unsetClaim("iss");
  claims.unsetClaim("aud");
  claims.unsetClaim("exp");
  jws.setPayload(claims.toJson());
  String slimJwt = jws.getCompactSerialization();
  slimHeader = "Bearer" + " " + slimJwt;
}
 
Example #14
Source File: JwtCachingAuthenticatorTest.java    From dropwizard-auth-jwt with Apache License 2.0 6 votes vote down vote up
private JwtContext tokenTwo() {
    final JwtClaims claims = new JwtClaims();
    claims.setSubject("good-guy-two");
    claims.setIssuer("Issuer");
    claims.setAudience("Audience");

    final JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA512);
    jws.setKey(new HmacKey(SECRET.getBytes(UTF_8)));
    jws.setDoKeyValidation(false);

    try {
        return consumer.process(jws.getCompactSerialization());
    }
    catch (Exception e) { throw Throwables.propagate(e); }
}
 
Example #15
Source File: JwtSignEncryptTest.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
private static void checkClaimsAndJwsHeaders(String jwsCompact, JwtClaims claims, String algo, String keyId)
        throws Exception {
    Assert.assertNotNull(claims.getIssuedAt());
    Assert.assertNotNull(claims.getExpirationTime());
    Assert.assertNotNull(claims.getJwtId());

    Map<String, Object> headers = getJwsHeaders(jwsCompact);
    Assert.assertEquals(keyId != null ? 3 : 2, headers.size());
    Assert.assertEquals(algo, headers.get("alg"));
    Assert.assertEquals("JWT", headers.get("typ"));
    if (keyId != null) {
        Assert.assertEquals(keyId, headers.get("kid"));
    } else {
        Assert.assertNull(headers.get("kid"));
    }
}
 
Example #16
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 #17
Source File: OauthHelperTest.java    From light-4j with Apache License 2.0 5 votes vote down vote up
public static String getJwt(JwtClaims claims) throws JoseException {
    String jwt;

    RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey(
            "/config/primary.jks", "password", "selfsigned");

    // A JWT is a JWS and/or a JWE with JSON claims as the payload.
    // In this example it is a JWS nested inside a JWE
    // So we first create a JsonWebSignature object.
    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);
    jws.setKeyIdHeaderValue("100");

    // 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();
    return jwt;
}
 
Example #18
Source File: GoogsTooSmallKeyJwtConsumerTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void firstWorkaroundUsingTwoPass() throws Exception
{
    // Build a JwtConsumer that doesn't check signatures or do any validation.
    JwtConsumer firstPassJwtConsumer = new JwtConsumerBuilder()
            .setSkipAllValidators()
            .setDisableRequireSignature()
            .setSkipSignatureVerification()
            .build();

    //The first JwtConsumer is basically just used to parse the JWT into a JwtContext object.
    JwtContext jwtContext = firstPassJwtConsumer.process(ID_TOKEN);

    // turn off key key validation (chiefly the enforcement of RSA 2048 as min key size) on the the inner most JOSE object (the JWS)
    jwtContext.getJoseObjects().iterator().next().setDoKeyValidation(false);

    JsonWebKeySet jwks = new JsonWebKeySet(JWKS_JSON);
    JwksVerificationKeyResolver verificationKeyResolver = new JwksVerificationKeyResolver(jwks.getJsonWebKeys());

    JwtConsumer jwtConsumer = new JwtConsumerBuilder()
            .setRequireExpirationTime() // the JWT must have an expiration time
            .setEvaluationTime(EVALUATION_TIME)
            .setRequireSubject() // the JWT must have a subject claim
            .setExpectedIssuer(ISSUER)
            .setExpectedAudience(CLIENT_ID) // to whom the JWT is intended for
            .setVerificationKeyResolver(verificationKeyResolver) // pretend to use Google's jwks endpoint to find the key for signature checks
            .build(); // create the JwtConsumer instance

    jwtConsumer.processContext(jwtContext);
    JwtClaims jwtClaims = jwtContext.getJwtClaims();
    assertThat(SUBJECT_VALUE, equalTo(jwtClaims.getSubject()));
}
 
Example #19
Source File: DefaultJWTTokenParser.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
private void checkNameClaims(JwtContext jwtContext) throws InvalidJwtException {
    JwtClaims claimsSet = jwtContext.getJwtClaims();
    final boolean hasPrincipalClaim = claimsSet.getClaimValue(Claims.sub.name()) != null ||
            claimsSet.getClaimValue(Claims.upn.name()) != null ||
            claimsSet.getClaimValue(Claims.preferred_username.name()) != null;

    if (!hasPrincipalClaim) {
        throw PrincipalMessages.msg.claimNotFound(s -> new InvalidJwtException(s, emptyList(), jwtContext));
    }
}
 
Example #20
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 #21
Source File: JwtBuilder.java    From microprofile-sandbox with Apache License 2.0 5 votes vote down vote up
public static String buildJwt(String subject, String issuer, String[] claims) {
	me = new JwtBuilder();
	init();
	me.claims = new JwtClaims();
	me.jws = new JsonWebSignature();

	me.jws.setKeyIdHeaderValue(rsajwk.getKeyId());
	me.jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
	// The JWT is signed using the private key, get the key we'll use every time.
	me.jws.setKey(rsajwk.getPrivateKey());
	if (subject != null) {
		me.claims.setClaim("sub", subject);
		me.claims.setClaim("upn", subject);
	}
	me.claims.setIssuer(DEFAULT_ISSUER);
	me.claims.setExpirationTimeMinutesInTheFuture(60);
	if (issuer != null) {
		me.claims.setIssuer(issuer);
	}
	setClaims(claims);
	try {
		if (me.claims.getIssuedAt() == null) {
			me.claims.setIssuedAtToNow();
		}
	} catch (MalformedClaimException e1) {
		e1.printStackTrace(System.out);
	}
	me.jws.setPayload(me.claims.toJson());
	try {
		return me.jws.getCompactSerialization();
	} catch (JoseException e) {
		e.printStackTrace(System.out);
		return null;
	}

}
 
Example #22
Source File: Token.java    From server_face_recognition with GNU General Public License v3.0 5 votes vote down vote up
public static Token decypherToken(String token) {
    JwtConsumer jwtConsumer = new JwtConsumerBuilder()
            .setRequireExpirationTime()
            .setAllowedClockSkewInSeconds(30)
            .setRequireSubject()
            .setExpectedIssuer("Sanstorik")
            .setExpectedAudience("User")
            .setVerificationKey(key.getKey())
            .setJwsAlgorithmConstraints(
                    new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.WHITELIST,
                            AlgorithmIdentifiers.RSA_USING_SHA256))
            .build();

    Token decypheredToken = null;
    try
    {
        JwtClaims jwtClaims = jwtConsumer.processToClaims(token);
        decypheredToken = new Token(token,
             jwtClaims.getClaimValue(USERNAME_KEY).toString(),
             jwtClaims.getClaimValue(PASSWORD_KEY).toString(),
             Integer.valueOf(jwtClaims.getClaimValue(USERID_KEY).toString())
        );
    } catch (InvalidJwtException e) {
        e.printStackTrace();
    }

    return decypheredToken;
}
 
Example #23
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 #24
Source File: DownloadController.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Validate a given token for a given channel.
 *
 * @param token the token to validate
 * @param channel the channel
 * @param filename the filename
 */
private static void validateToken(String token, String channel, String filename) {
    AccessTokenFactory.lookupByToken(token).ifPresent(obj -> {
        if (!obj.getValid()) {
            halt(HttpStatus.SC_FORBIDDEN, "This token is not valid");
        }
    });
    try {
        JwtClaims claims = JWT_CONSUMER.processToClaims(token);

        // enforce channel claim
        Optional<List<String>> channelClaim = Optional.ofNullable(claims.getStringListClaimValue("onlyChannels"))
                // new versions of getStringListClaimValue() return an empty list instead of null
                .filter(l -> !l.isEmpty());
        if (Opt.fold(channelClaim, () -> false, channels -> !channels.contains(channel))) {
            halt(HttpStatus.SC_FORBIDDEN, "Token does not provide access to channel " + channel);
        }

        // enforce org claim
        Optional<Long> orgClaim = Optional.ofNullable(claims.getClaimValue("org", Long.class));
        Opt.consume(orgClaim, () -> {
            halt(HttpStatus.SC_BAD_REQUEST, "Token does not specify the organization");
        }, orgId -> {
            if (!ChannelFactory.isAccessibleBy(channel, orgId)) {
                halt(HttpStatus.SC_FORBIDDEN, "Token does not provide access to channel %s" + channel);
            }
        });
    }
    catch (InvalidJwtException | MalformedClaimException e) {
        halt(HttpStatus.SC_FORBIDDEN,
             String.format("Token is not valid to access %s in %s: %s", filename, channel, e.getMessage()));
    }
}
 
Example #25
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 #26
Source File: WebSockifyTokenBuilder.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
@Override
public JwtClaims getClaims() {
    JwtClaims claims = super.getClaims();
    claims.setClaim("host", this.host);
    claims.setClaim("port", this.port);
    return claims;
}
 
Example #27
Source File: WebIdPrincipalTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testIssNoSlashPrincipal() {
    final String iss = "http://idp.example.com";
    final String sub = "acoburn";
    final JwtClaims claims = new JwtClaims();
    claims.setSubject(sub);
    claims.setIssuer(iss);
    final JsonWebToken principal = new WebIdPrincipal(new DefaultJWTCallerPrincipal(claims));
    assertTrue(principal.getClaimNames().contains("sub"));
    assertEquals(iss + "/" + sub, principal.getName());
    assertEquals(iss, principal.getIssuer());
    assertEquals(iss, principal.getClaim("iss"));
}
 
Example #28
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 #29
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 #30
Source File: JWTCredential.java    From thorntail with Apache License 2.0 5 votes vote down vote up
/**
 * This just parses the token without validation to extract one of the following in order to obtain
 * the name to be used for the principal:
 * upn
 * preferred_username
 * subject
 *
 * If there is an exception it sets the name to INVALID_TOKEN_NAME and saves the exception for access
 * via {@link #getJwtException()}
 *
 * @return the name to use for the principal
 */
public String getName() {
    if (name == null) {
        name = "INVALID_TOKEN_NAME";
        try {
            // Build a JwtConsumer that doesn't check signatures or do any validation.
            JwtConsumer firstPassJwtConsumer = new JwtConsumerBuilder()
                    .setSkipAllValidators()
                    .setDisableRequireSignature()
                    .setSkipSignatureVerification()
                    .build();

            //The first JwtConsumer is basically just used to parse the JWT into a JwtContext object.
            JwtContext jwtContext = firstPassJwtConsumer.process(bearerToken);
            JwtClaims claimsSet = jwtContext.getJwtClaims();
            // We have to determine the unique name to use as the principal name. It comes from upn, preferred_username, sub in that order
            name = claimsSet.getClaimValue("upn", String.class);
            if (name == null) {
                name = claimsSet.getClaimValue("preferred_username", String.class);
                if (name == null) {
                    name = claimsSet.getSubject();
                }
            }
        } catch (Exception e) {
            jwtException = e;
        }
    }
    return name;
}