org.apache.cxf.rs.security.jose.jws.JwsHeaders Java Examples

The following examples show how to use org.apache.cxf.rs.security.jose.jws.JwsHeaders. 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: AbstractOIDCTest.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
private void validateIdToken(String idToken, String audience, String role) throws IOException {
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(idToken);
    JwtToken jwt = jwtConsumer.getJwtToken();
    JwtClaims jwtClaims = jwt.getClaims();

    // Validate claims
    assertEquals("alice", jwtClaims.getClaim("preferred_username"));
    assertEquals("accounts.fediz.com", jwtClaims.getIssuer());
    assertEquals(audience, jwtClaims.getAudience());
    assertNotNull(jwtClaims.getIssuedAt());
    assertNotNull(jwtClaims.getExpiryTime());

    // Check role
    if (role != null) {
        List<String> roles = jwtClaims.getListStringProperty("roles");
        assertNotNull(roles);
        assertTrue(roles.contains(role));
    }

    JwsHeaders jwsHeaders = jwt.getJwsHeaders();
    assertTrue(jwtConsumer.verifySignatureWith(
        jsonWebKeys().getKey(jwsHeaders.getKeyId()), SignatureAlgorithm.valueOf(jwsHeaders.getAlgorithm())));
}
 
Example #2
Source File: BigQueryServer.java    From cxf with Apache License 2.0 6 votes vote down vote up
private static ClientAccessToken getAccessToken(PrivateKey privateKey, String issuer) {
    JwsHeaders headers = new JwsHeaders(JoseType.JWT, SignatureAlgorithm.RS256);
    JwtClaims claims = new JwtClaims();
    claims.setIssuer(issuer);
    claims.setAudience("https://www.googleapis.com/oauth2/v3/token");

    long issuedAt = OAuthUtils.getIssuedAt();
    claims.setIssuedAt(issuedAt);
    claims.setExpiryTime(issuedAt + 60 * 60);
    claims.setProperty("scope", "https://www.googleapis.com/auth/bigquery.readonly");

    JwtToken token = new JwtToken(headers, claims);
    JwsJwtCompactProducer p = new JwsJwtCompactProducer(token);
    String base64UrlAssertion = p.signWith(privateKey);

    JwtBearerGrant grant = new JwtBearerGrant(base64UrlAssertion);

    WebClient accessTokenService = WebClient.create("https://www.googleapis.com/oauth2/v3/token",
                                                    Arrays.asList(new OAuthJSONProvider(),
                                                                  new AccessTokenGrantWriter()));
    WebClient.getConfig(accessTokenService).getInInterceptors().add(new LoggingInInterceptor());

    accessTokenService.type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_JSON);

    return accessTokenService.post(grant, ClientAccessToken.class);
}
 
Example #3
Source File: ApacheCXFProducer.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void produceJWS(String keyType, String signatureAlgorithm, Serialization serialization, String plainText,
    String jwksJson) {
    JsonWebKeys keys = JwkUtils.readJwkSet(jwksJson);
    JsonWebKey key = getRequestedKeyType(keyType, keys).orElseThrow(IllegalArgumentException::new);

    // Sign
    JwsHeaders jwsHeaders = new JwsHeaders();
    jwsHeaders.setKeyId(key.getKeyId());
    jwsHeaders.setAlgorithm(signatureAlgorithm);
    switch (serialization) {
    case COMPACT:
        produceCompactJWS(plainText, key, jwsHeaders);
        break;
    case FLATTENED:
        produceJsonJWS(plainText, key, jwsHeaders, true);
        break;
    case JSON:
        produceJsonJWS(plainText, key, jwsHeaders, false);
        break;
    default:
        throw new IllegalArgumentException("Serialization not supported: " + serialization);
    }

}
 
Example #4
Source File: DefaultJoseImpl.java    From thorntail with Apache License 2.0 6 votes vote down vote up
@Override
public String sign(SignatureInput input) {
    JwsHeaders headers = new JwsHeaders();
    headers.asMap().putAll(input.getHeaders());
    if (!config.signatureDataEncoding()) {
        headers.setPayloadEncodingStatus(false);
    }
    if (config.includeSignatureKeyAlias()) {
        headers.setKeyId(signatureKeyAlias());
    }
    Properties props = prepareSignatureVerificationProperties(JoseOperation.SIGN);
    headers.setSignatureAlgorithm(SignatureAlgorithm.getAlgorithm(config.signatureAlgorithm()));
    JwsSignatureProvider provider = getSignatureProvider(props, headers);

    return DEFAULT_JOSE_FORMAT == config.signatureFormat()
            ? signCompact(provider, headers, input.getData()) : signJson(provider, headers, input.getData());
}
 
Example #5
Source File: DefaultJoseImpl.java    From thorntail with Apache License 2.0 5 votes vote down vote up
private JwsSignatureVerifier getJwsSignatureVerifier(Properties props, JwsHeaders headers) {
    if (config.acceptSignatureAlias()) {
        props.setProperty(JoseConstants.RSSEC_KEY_STORE_ALIAS, headers.getKeyId());
    }

    if (isInlinedJwkSetAvailable()) {
        return JwsUtils.getSignatureVerifier(loadJsonWebKey(verificationKeyAlias()));
    } else {
        return JwsUtils.loadSignatureVerifier(props, headers);
    }
}
 
Example #6
Source File: DefaultJoseImpl.java    From thorntail with Apache License 2.0 5 votes vote down vote up
private JwsSignatureProvider getSignatureProvider(Properties props, JwsHeaders headers) {
    if (isInlinedJwkSetAvailable()) {
        return JwsUtils.getSignatureProvider(loadJsonWebKey(signatureKeyAlias()));
    } else {
        return JwsUtils.loadSignatureProvider(props, headers);
    }
}
 
Example #7
Source File: JwsJoseCookBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testProtectingContentOnlySignature() throws Exception {
    JwsJsonProducer jsonProducer = new JwsJsonProducer(PAYLOAD);
    assertEquals(jsonProducer.getPlainPayload(), PAYLOAD);
    assertEquals(jsonProducer.getUnsignedEncodedPayload(), ENCODED_PAYLOAD);
    JwsHeaders unprotectedHeader = new JwsHeaders();
    unprotectedHeader.setSignatureAlgorithm(SignatureAlgorithm.HS256);
    unprotectedHeader.setKeyId(HMAC_KID_VALUE);
    JsonWebKeys jwks = readKeySet("cookbookSecretSet.txt");
    List<JsonWebKey> keys = jwks.getKeys();
    JsonWebKey key = keys.get(0);
    jsonProducer.signWith(JwsUtils.getSignatureProvider(key, SignatureAlgorithm.HS256),
            null, unprotectedHeader);
    assertEquals(jsonProducer.getJwsJsonSignedDocument(),
            PROTECTING_CONTENT_ONLY_JSON_GENERAL_SERIALIZATION);
    JwsJsonConsumer jsonConsumer =
            new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument());
    assertTrue(jsonConsumer.verifySignatureWith(key, SignatureAlgorithm.HS256));

    jsonProducer = new JwsJsonProducer(PAYLOAD, true);
    jsonProducer.signWith(JwsUtils.getSignatureProvider(key, SignatureAlgorithm.HS256),
            null, unprotectedHeader);
    assertEquals(jsonProducer.getJwsJsonSignedDocument(),
            PROTECTING_CONTENT_ONLY_JSON_FLATTENED_SERIALIZATION);
    jsonConsumer = new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument());
    assertTrue(jsonConsumer.verifySignatureWith(key, SignatureAlgorithm.HS256));
}
 
Example #8
Source File: TokenCache.java    From g-suite-identity-sync with Apache License 2.0 5 votes vote down vote up
private ClientAccessToken getAccessToken() throws NoPrivateKeyException {
    JwsHeaders headers = new JwsHeaders(JoseType.JWT, SignatureAlgorithm.RS256);
    JwtClaims claims = new JwtClaims();
    claims.setIssuer(config.getServiceAccountEmail());
    claims.setAudience(config.getServiceAccountTokenUri());
    claims.setSubject(config.getServiceAccountSubject());

    long issuedAt = OAuthUtils.getIssuedAt();
    long tokenTimeout = config.getServiceAccountTokenLifetime();
    claims.setIssuedAt(issuedAt);
    claims.setExpiryTime(issuedAt + tokenTimeout);
    String scopes = String.join(" ", config.getServiceAccountScopes());
    claims.setProperty("scope", scopes);

    JwtToken token = new JwtToken(headers, claims);
    JwsJwtCompactProducer p = new JwsJwtCompactProducer(token);
    String base64UrlAssertion = p.signWith(config.readServiceAccountKey());

    JwtBearerGrant grant = new JwtBearerGrant(base64UrlAssertion);

    WebClient accessTokenService = WebClient.create(config.getServiceAccountTokenUri(),
            Arrays.asList(new OAuthJSONProvider(), new AccessTokenGrantWriter()));

    accessTokenService.type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_JSON);

    return accessTokenService.post(grant, ClientAccessToken.class);
}
 
Example #9
Source File: JWTITCase.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Test
public void tokenValidation() throws ParseException {
    // Get an initial token
    SyncopeClient localClient = clientFactory.create(ADMIN_UNAME, ADMIN_PWD);
    AccessTokenService accessTokenService = localClient.getService(AccessTokenService.class);

    Response response = accessTokenService.login();
    String token = response.getHeaderString(RESTHeaders.TOKEN);
    assertNotNull(token);
    JwsJwtCompactConsumer consumer = new JwsJwtCompactConsumer(token);
    String tokenId = consumer.getJwtClaims().getTokenId();

    // Create a new token using the Id of the first token
    Date now = new Date();
    long currentTime = now.getTime() / 1000L;

    Calendar expiry = Calendar.getInstance();
    expiry.setTime(now);
    expiry.add(Calendar.MINUTE, 5);

    JwtClaims jwtClaims = new JwtClaims();
    jwtClaims.setTokenId(tokenId);
    jwtClaims.setSubject(ADMIN_UNAME);
    jwtClaims.setIssuedAt(currentTime);
    jwtClaims.setIssuer(JWT_ISSUER);
    jwtClaims.setExpiryTime(expiry.getTime().getTime() / 1000L);
    jwtClaims.setNotBefore(currentTime);

    JwsHeaders jwsHeaders = new JwsHeaders(JoseType.JWT, JWS_ALGORITHM);
    JwtToken jwtToken = new JwtToken(jwsHeaders, jwtClaims);
    JwsJwtCompactProducer producer = new JwsJwtCompactProducer(jwtToken);

    String signed = producer.signWith(jwsSignatureProvider);

    SyncopeClient jwtClient = clientFactory.create(signed);
    UserSelfService jwtUserSelfService = jwtClient.getService(UserSelfService.class);
    jwtUserSelfService.read();
}
 
Example #10
Source File: JwsJoseCookBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testProtectingSpecificHeaderFieldsSignature() throws Exception {
    JwsJsonProducer jsonProducer = new JwsJsonProducer(PAYLOAD);
    assertEquals(jsonProducer.getPlainPayload(), PAYLOAD);
    assertEquals(jsonProducer.getUnsignedEncodedPayload(), ENCODED_PAYLOAD);
    JwsHeaders protectedHeader = new JwsHeaders();
    protectedHeader.setSignatureAlgorithm(SignatureAlgorithm.HS256);
    JwsHeaders unprotectedHeader = new JwsHeaders();
    unprotectedHeader.setKeyId(HMAC_KID_VALUE);
    JsonWebKeys jwks = readKeySet("cookbookSecretSet.txt");
    List<JsonWebKey> keys = jwks.getKeys();
    JsonWebKey key = keys.get(0);
    jsonProducer.signWith(JwsUtils.getSignatureProvider(key, SignatureAlgorithm.HS256),
            protectedHeader, unprotectedHeader);
    assertEquals(jsonProducer.getJwsJsonSignedDocument(),
            PROTECTING_SPECIFIC_HEADER_FIELDS_JSON_GENERAL_SERIALIZATION);
    JwsJsonConsumer jsonConsumer =
            new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument());
    assertTrue(jsonConsumer.verifySignatureWith(key, SignatureAlgorithm.HS256));

    jsonProducer = new JwsJsonProducer(PAYLOAD, true);
    jsonProducer.signWith(JwsUtils.getSignatureProvider(key, SignatureAlgorithm.HS256),
            protectedHeader, unprotectedHeader);
    assertEquals(jsonProducer.getJwsJsonSignedDocument(),
            PROTECTING_SPECIFIC_HEADER_FIELDS_JSON_FLATTENED_SERIALIZATION);
    jsonConsumer = new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument());
    assertTrue(jsonConsumer.verifySignatureWith(key, SignatureAlgorithm.HS256));
}
 
Example #11
Source File: DefaultJoseImpl.java    From thorntail with Apache License 2.0 5 votes vote down vote up
private String signCompact(JwsSignatureProvider provider, JwsHeaders headers, String data) {
    try {
        JwsCompactProducer producer = new JwsCompactProducer(headers, data, config.signatureDataDetached());
        return producer.signWith(provider);
    } catch (Exception ex) {
        throw new JoseException("JWS Compact Signature Creation Failure", ex);
    }
}
 
Example #12
Source File: JwsJoseCookBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testRSAv15Signature() throws Exception {
    JwsCompactProducer compactProducer = new JwsCompactProducer(PAYLOAD);
    compactProducer.getJwsHeaders().setSignatureAlgorithm(SignatureAlgorithm.RS256);
    compactProducer.getJwsHeaders().setKeyId(RSA_KID_VALUE);
    JsonMapObjectReaderWriter reader = new JsonMapObjectReaderWriter();
    assertEquals(reader.toJson(compactProducer.getJwsHeaders().asMap()), RSA_V1_5_SIGNATURE_PROTECTED_HEADER_JSON);
    assertEquals(compactProducer.getUnsignedEncodedJws(),
            RSA_V1_5_SIGNATURE_PROTECTED_HEADER + "." + ENCODED_PAYLOAD);
    JsonWebKeys jwks = readKeySet("cookbookPrivateSet.txt");
    List<JsonWebKey> keys = jwks.getKeys();
    JsonWebKey rsaKey = keys.get(1);
    compactProducer.signWith(rsaKey);
    assertEquals(compactProducer.getSignedEncodedJws(),
            RSA_V1_5_SIGNATURE_PROTECTED_HEADER + "." + ENCODED_PAYLOAD + "." + RSA_V1_5_SIGNATURE_VALUE);
    JwsCompactConsumer compactConsumer = new JwsCompactConsumer(compactProducer.getSignedEncodedJws());
    JsonWebKeys publicJwks = readKeySet("cookbookPublicSet.txt");
    List<JsonWebKey> publicKeys = publicJwks.getKeys();
    JsonWebKey rsaPublicKey = publicKeys.get(1);
    assertTrue(compactConsumer.verifySignatureWith(rsaPublicKey,
                                                   SignatureAlgorithm.RS256));

    JwsJsonProducer jsonProducer = new JwsJsonProducer(PAYLOAD);
    assertEquals(jsonProducer.getPlainPayload(), PAYLOAD);
    assertEquals(jsonProducer.getUnsignedEncodedPayload(), ENCODED_PAYLOAD);
    JwsHeaders protectedHeader = new JwsHeaders();
    protectedHeader.setSignatureAlgorithm(SignatureAlgorithm.RS256);
    protectedHeader.setKeyId(RSA_KID_VALUE);
    jsonProducer.signWith(JwsUtils.getSignatureProvider(rsaKey,
                                                        SignatureAlgorithm.RS256), protectedHeader);
    assertEquals(jsonProducer.getJwsJsonSignedDocument(), RSA_V1_5_JSON_GENERAL_SERIALIZATION);
    JwsJsonConsumer jsonConsumer = new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument());
    assertTrue(jsonConsumer.verifySignatureWith(rsaPublicKey, SignatureAlgorithm.RS256));

    jsonProducer = new JwsJsonProducer(PAYLOAD, true);
    jsonProducer.signWith(JwsUtils.getSignatureProvider(rsaKey, SignatureAlgorithm.RS256), protectedHeader);
    assertEquals(jsonProducer.getJwsJsonSignedDocument(), RSA_V1_5_JSON_FLATTENED_SERIALIZATION);
    jsonConsumer = new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument());
    assertTrue(jsonConsumer.verifySignatureWith(rsaPublicKey, SignatureAlgorithm.RS256));
}
 
Example #13
Source File: JwsWriterInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void protectHttpHeadersIfNeeded(WriterInterceptorContext ctx, JwsHeaders jwsHeaders) {
    if (protectHttpHeaders) {
        JoseJaxrsUtils.protectHttpHeaders(ctx.getHeaders(), 
                                          jwsHeaders, 
                                          protectedHttpHeaders);
    }
    
}
 
Example #14
Source File: AbstractJoseConsumer.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected JwsSignatureVerifier getInitializedSignatureVerifier(JwsHeaders jwsHeaders) {
    if (jwsVerifier != null) {
        return jwsVerifier;
    }

    return JwsUtils.loadSignatureVerifier(jwsHeaders, false);
}
 
Example #15
Source File: AccessTokenDataBinderImpl.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
public Pair<String, Date> generateJWT(
        final String tokenId,
        final String subject,
        final long duration,
        final Map<String, Object> claims) {

    credentialChecker.checkIsDefaultJWSKeyInUse();

    long currentTime = new Date().getTime() / 1000L;
    long expiryTime = currentTime + 60L * duration;

    JwtClaims jwtClaims = new JwtClaims();
    jwtClaims.setTokenId(tokenId);
    jwtClaims.setSubject(subject);
    jwtClaims.setIssuedAt(currentTime);
    jwtClaims.setIssuer(jwtIssuer);
    jwtClaims.setExpiryTime(expiryTime);
    jwtClaims.setNotBefore(currentTime);
    claims.forEach(jwtClaims::setClaim);

    JwsHeaders jwsHeaders = new JwsHeaders(JoseType.JWT, jwsSignatureProvider.getAlgorithm());
    JwtToken token = new JwtToken(jwsHeaders, jwtClaims);
    JwsJwtCompactProducer producer = new JwsJwtCompactProducer(token);

    String signed = producer.signWith(jwsSignatureProvider);

    return Pair.of(signed, new Date(expiryTime * 1000L));
}
 
Example #16
Source File: AccessTokenDataBinderImpl.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
public Pair<String, Date> update(final AccessToken accessToken, final byte[] authorities) {
    JwsJwtCompactConsumer consumer = new JwsJwtCompactConsumer(accessToken.getBody());

    credentialChecker.checkIsDefaultJWSKeyInUse();

    long duration = confParamOps.get(AuthContextUtils.getDomain(), "jwt.lifetime.minutes", 120L, Long.class);
    long currentTime = new Date().getTime() / 1000L;
    long expiry = currentTime + 60L * duration;
    consumer.getJwtClaims().setExpiryTime(expiry);
    Date expiryDate = new Date(expiry * 1000L);

    JwsHeaders jwsHeaders = new JwsHeaders(JoseType.JWT, jwsSignatureProvider.getAlgorithm());
    JwtToken token = new JwtToken(jwsHeaders, consumer.getJwtClaims());
    JwsJwtCompactProducer producer = new JwsJwtCompactProducer(token);

    String body = producer.signWith(jwsSignatureProvider);

    accessToken.setBody(body);
    // AccessToken stores expiry time in milliseconds, as opposed to seconds for the JWT tokens.
    accessToken.setExpiryTime(expiryDate);

    if (!adminUser.equals(accessToken.getOwner())) {
        accessToken.setAuthorities(authorities);
    }

    accessTokenDAO.save(accessToken);

    return Pair.of(body, expiryDate);
}
 
Example #17
Source File: JwsJoseCookBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testDetachedHMACSignature2() throws Exception {
    JsonWebKeys jwks = readKeySet("cookbookSecretSet.txt");
    List<JsonWebKey> keys = jwks.getKeys();
    JsonWebKey key = keys.get(0);
    
    JwsJsonProducer jsonProducer = new JwsJsonProducer(PAYLOAD, false, true);
    assertEquals(jsonProducer.getPlainPayload(), PAYLOAD);
    assertEquals(jsonProducer.getUnsignedEncodedPayload(), ENCODED_PAYLOAD);
    JwsHeaders protectedHeader = new JwsHeaders();
    protectedHeader.setSignatureAlgorithm(SignatureAlgorithm.HS256);
    protectedHeader.setKeyId(HMAC_KID_VALUE);
    
    String jwsJsonCompleteSequence = 
        jsonProducer.signWith(JwsUtils.getSignatureProvider(key, SignatureAlgorithm.HS256), protectedHeader);
    assertEquals(jwsJsonCompleteSequence, HMAC_DETACHED_JSON_GENERAL_SERIALIZATION);
    JwsJsonConsumer jsonConsumer =
            new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument(), ENCODED_PAYLOAD);
    assertTrue(jsonConsumer.verifySignatureWith(key, SignatureAlgorithm.HS256));

    jsonProducer = new JwsJsonProducer(PAYLOAD, true, true);
    String jwsJsonFlattenedSequence = 
        jsonProducer.signWith(JwsUtils.getSignatureProvider(key, SignatureAlgorithm.HS256), protectedHeader);
    assertEquals(jwsJsonFlattenedSequence, HMAC_DETACHED_JSON_FLATTENED_SERIALIZATION);
    jsonConsumer = new JwsJsonConsumer(jwsJsonFlattenedSequence, ENCODED_PAYLOAD);
    assertTrue(jsonConsumer.verifySignatureWith(key, SignatureAlgorithm.HS256));
}
 
Example #18
Source File: OIDCFlowTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testAuthorizationCodeFlowUnsignedJWT() throws Exception {
    URL busFile = OIDCFlowTest.class.getResource("client.xml");

    String address = "https://localhost:" + port + "/unsignedjwtservices/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    JwtClaims claims = new JwtClaims();
    claims.setIssuer("consumer-id");
    claims.setIssuedAt(Instant.now().getEpochSecond());
    claims.setAudiences(
        Collections.singletonList("https://localhost:" + port + "/unsignedjwtservices/"));

    JwsHeaders headers = new JwsHeaders();
    headers.setAlgorithm("none");

    JwtToken token = new JwtToken(headers, claims);

    JwsJwtCompactProducer jws = new JwsJwtCompactProducer(token);
    String request = jws.getSignedEncodedJws();

    // Get Authorization Code
    AuthorizationCodeParameters parameters = new AuthorizationCodeParameters();
    parameters.setConsumerId("consumer-id");
    parameters.setScope("openid");
    parameters.setResponseType("code");
    parameters.setPath("authorize/");
    parameters.setRequest(request);

    String location = OAuth2TestUtils.getLocation(client, parameters);
    String code = OAuth2TestUtils.getSubstring(location, "code");
    assertNotNull(code);
}
 
Example #19
Source File: OIDCFlowTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testAuthorizationCodeFlowUnsignedJWTWithState() throws Exception {
    URL busFile = OIDCFlowTest.class.getResource("client.xml");

    String address = "https://localhost:" + port + "/unsignedjwtservices/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    JwtClaims claims = new JwtClaims();
    claims.setIssuer("consumer-id");
    claims.setIssuedAt(Instant.now().getEpochSecond());
    claims.setAudiences(
        Collections.singletonList("https://localhost:" + port + "/unsignedjwtservices/"));

    JwsHeaders headers = new JwsHeaders();
    headers.setAlgorithm("none");

    JwtToken token = new JwtToken(headers, claims);

    JwsJwtCompactProducer jws = new JwsJwtCompactProducer(token);
    String request = jws.getSignedEncodedJws();

    // Get Authorization Code
    AuthorizationCodeParameters parameters = new AuthorizationCodeParameters();
    parameters.setConsumerId("consumer-id");
    parameters.setScope("openid");
    parameters.setResponseType("code");
    parameters.setPath("authorize/");
    parameters.setState("123456789");
    parameters.setRequest(request);

    String location = OAuth2TestUtils.getLocation(client, parameters);
    String code = OAuth2TestUtils.getSubstring(location, "code");
    assertNotNull(code);
}
 
Example #20
Source File: AbstractJoseProducer.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected JwsSignatureProvider getInitializedSignatureProvider(JwsHeaders jwsHeaders) {
    if (sigProvider != null) {
        return sigProvider;
    }

    return JwsUtils.loadSignatureProvider(jwsHeaders, false);
}
 
Example #21
Source File: JoseProducer.java    From cxf with Apache License 2.0 5 votes vote down vote up
public String processData(String data) {
    super.checkProcessRequirements();
    
    JweEncryptionProvider theEncProvider = null;
    JweHeaders jweHeaders = new JweHeaders();
    if (isJweRequired()) {
        theEncProvider = getInitializedEncryptionProvider(jweHeaders);
        if (theEncProvider == null) {
            throw new JoseException("Unable to encrypt the data");
        }
    }

    if (isJwsRequired()) {
        JwsHeaders jwsHeaders = new JwsHeaders();
        JwsCompactProducer jws = new JwsCompactProducer(jwsHeaders, data);
        
        JwsSignatureProvider theSigProvider = getInitializedSignatureProvider(jwsHeaders);
        
        if (theSigProvider == null) {
            throw new JoseException("Unable to sign the data");
        }

        data = jws.signWith(theSigProvider);
        
    }
    if (theEncProvider != null) {
        data = theEncProvider.encrypt(StringUtils.toBytesUTF8(data), jweHeaders);
    }
    return data;
}
 
Example #22
Source File: JoseUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static void traceHeaders(JoseHeaders headers) {
    Message m = PhaseInterceptorChain.getCurrentMessage();
    if (MessageUtils.getContextualBoolean(m, JoseConstants.JOSE_DEBUG, false)) {
        JsonMapObjectReaderWriter writer = new JsonMapObjectReaderWriter(true);
        String thePrefix = headers instanceof JwsHeaders ? "JWS" : headers instanceof JweHeaders ? "JWE" : "JOSE";
        LOG.info(thePrefix + " Headers: \r\n" + writer.toJson(headers));
    }
}
 
Example #23
Source File: TestJwts.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
static String createSigned(JwtToken baseJwt, JsonWebKey jwk, JwsSignatureProvider signatureProvider) {
	JwsHeaders jwsHeaders = new JwsHeaders();
	JwtToken signedToken = new JwtToken(jwsHeaders, baseJwt.getClaims());

	jwsHeaders.setKeyId(jwk.getKeyId());

       return new JoseJwtProducer().processJwt(signedToken, null, signatureProvider);
}
 
Example #24
Source File: JwsJwksJwtAccessTokenValidatorTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetInitializedSignatureVerifier() {
    final JsonWebKey jwk = new JsonWebKey();
    jwk.setKeyId("anyKid");
    jwk.setPublicKeyUse(PublicKeyUse.ENCRYPT);
    final JsonWebKey jwk1 = new JsonWebKey();
    jwk1.setKeyId("kid1");
    final JsonWebKey jwk2 = new JsonWebKey();
    jwk2.setKeyId("kid2");
    jwk2.setPublicKeyUse(PublicKeyUse.SIGN);
    final JsonWebKey jwk3 = new JsonWebKey();
    jwk3.setKeyId("kid3");
    jwk3.setPublicKeyUse(PublicKeyUse.SIGN);

    final JwsJwksJwtAccessTokenValidator validator = new JwsJwksJwtAccessTokenValidator() {
        int invokeCnt;
        @Override
        JsonWebKeys getJsonWebKeys() {
            ++invokeCnt;
            if (invokeCnt == 1) {
                return new JsonWebKeys(Arrays.asList(jwk, jwk1, jwk2));
            } else if (invokeCnt == 2) {
                return new JsonWebKeys(Arrays.asList(jwk, jwk1, jwk3));
            }
            throw new IllegalStateException();
        }
    };
    validator.setJwksURL("https://any.url");

    validator.getInitializedSignatureVerifier(new JwsHeaders(jwk2.getKeyId()));
    assertEquals(new HashSet<>(Arrays.asList(jwk1.getKeyId(), jwk2.getKeyId())),
        validator.jsonWebKeys.keySet());

    // rotate keys
    validator.getInitializedSignatureVerifier(new JwsHeaders(jwk3.getKeyId()));
    assertEquals(new HashSet<>(Arrays.asList(jwk1.getKeyId(), jwk3.getKeyId())),
        validator.jsonWebKeys.keySet());
}
 
Example #25
Source File: JwsJsonWriterInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void prepareProtectedHeader(JwsHeaders headers,
                                    WriterInterceptorContext ctx,
                                    JwsSignatureProvider signer,
                                    boolean protectHttp) {
    headers.setSignatureAlgorithm(signer.getAlgorithm());
    setContentTypeIfNeeded(headers, ctx);
    if (!encodePayload) {
        headers.setPayloadEncodingStatus(false);
    }
    if (protectHttp) {
        protectHttpHeadersIfNeeded(ctx, headers);
    }
}
 
Example #26
Source File: JwsJsonWriterInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void protectHttpHeadersIfNeeded(WriterInterceptorContext ctx, JwsHeaders jwsHeaders) {
    if (protectHttpHeaders) {
        JoseJaxrsUtils.protectHttpHeaders(ctx.getHeaders(), 
                                          jwsHeaders, 
                                          protectedHttpHeaders);
    }
    
}
 
Example #27
Source File: AbstractJwsMultipartSignatureFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected List<Object> getAttachmentParts(Object rootEntity) {
    List<Object> parts = null;
    
    if (rootEntity instanceof MultipartBody) {
        parts = CastUtils.cast(((MultipartBody)rootEntity).getAllAttachments());
    } else {
        parts = new ArrayList<>();
        if (rootEntity instanceof List) {
            List<Object> entityList = CastUtils.cast((List<?>)rootEntity);
            parts.addAll(entityList);
        } else {
            parts.add(rootEntity);
        }
    }
    
    JwsHeaders headers = new JwsHeaders();
    headers.setPayloadEncodingStatus(false);
    JwsSignatureProvider theSigProvider = sigProvider != null ? sigProvider
        : JwsUtils.loadSignatureProvider(headers, true);
    JwsSignature jwsSignature = theSigProvider.createJwsSignature(headers);
    
    String base64UrlEncodedHeaders = Base64UrlUtility.encode(writer.toJson(headers));
    byte[] headerBytesWithDot = StringUtils.toBytesASCII(base64UrlEncodedHeaders + ".");
    jwsSignature.update(headerBytesWithDot, 0, headerBytesWithDot.length);
    AttachmentUtils.addMultipartOutFilter(new JwsMultipartSignatureOutFilter(jwsSignature));
    
    
    JwsDetachedSignature jws = new JwsDetachedSignature(headers, 
                                                        base64UrlEncodedHeaders,
                                                        jwsSignature,
                                                        useJwsJsonSignatureFormat);
    
    Attachment jwsPart = new Attachment("signature", JoseConstants.MEDIA_TYPE_JOSE, jws);
    parts.add(jwsPart);
    return parts;
}
 
Example #28
Source File: AbstractJwsReaderProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected JwsSignatureVerifier getInitializedSigVerifier(JwsHeaders headers) {
    JoseUtils.traceHeaders(headers);
    if (sigVerifier != null) {
        return sigVerifier;
    }
    return JwsUtils.loadSignatureVerifier(headers, true);
}
 
Example #29
Source File: AbstractJwsJsonWriterProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected List<JwsSignatureProvider> getInitializedSigProviders(
    List<String> propLocs, List<JwsHeaders> protectedHeaders) {
    if (sigProviders != null) {
        return sigProviders;
    }
    Message m = JAXRSUtils.getCurrentMessage();
    List<JwsSignatureProvider> theSigProviders = new LinkedList<>();
    for (int i = 0; i < propLocs.size(); i++) {
        Properties props = JwsUtils.loadJwsProperties(m, propLocs.get(i));
        theSigProviders.add(JwsUtils.loadSignatureProvider(props, protectedHeaders.get(i)));
    }
    return theSigProviders;
}
 
Example #30
Source File: AbstractJwsWriterProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected JwsSignatureProvider getInitializedSigProvider(JwsHeaders headers) {
    setRequestContextProperty(headers);
    if (sigProvider != null) {
        return sigProvider;
    }
    return JwsUtils.loadSignatureProvider(headers, true);
}