Java Code Examples for org.apache.cxf.rs.security.jose.jws.JwsSignatureProvider

The following examples show how to use org.apache.cxf.rs.security.jose.jws.JwsSignatureProvider. These examples are extracted from open source projects. 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 Project: thorntail   Source File: DefaultJoseImpl.java    License: 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 2
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 3
static String createSignedWithPeculiarEscaping(JwtToken baseJwt, JsonWebKey jwk) {
	JwsSignatureProvider signatureProvider = JwsUtils.getSignatureProvider(jwk);
	JwsHeaders jwsHeaders = new JwsHeaders();
	JwtToken signedToken = new JwtToken(jwsHeaders, baseJwt.getClaims());

	// Depends on CXF not escaping the input string. This may fail for other frameworks or versions.
	jwsHeaders.setKeyId(jwk.getKeyId().replace("/", "\\/"));

	return new JoseJwtProducer().processJwt(signedToken, null, signatureProvider);
}
 
Example 4
Source Project: thorntail   Source File: DefaultJoseImpl.java    License: 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 5
Source Project: thorntail   Source File: DefaultJoseImpl.java    License: Apache License 2.0 5 votes vote down vote up
private String signJson(JwsSignatureProvider provider, JwsHeaders headers, String data) {
    try {
        JwsJsonProducer producer = new JwsJsonProducer(data, true, config.signatureDataDetached());
        return producer.signWith(provider, headers);
    } catch (Exception ex) {
        throw new JoseException("JWS JOSE Signature Creation Failure", ex);
    }
}
 
Example 6
Source Project: thorntail   Source File: DefaultJoseImpl.java    License: 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 Project: syncope   Source File: JWTITCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void noneSignature() 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
    JwtClaims jwtClaims = new JwtClaims();
    jwtClaims.setTokenId(tokenId);
    jwtClaims.setSubject(consumer.getJwtClaims().getSubject());
    jwtClaims.setIssuedAt(consumer.getJwtClaims().getIssuedAt());
    jwtClaims.setIssuer(consumer.getJwtClaims().getIssuer());
    jwtClaims.setExpiryTime(consumer.getJwtClaims().getExpiryTime());
    jwtClaims.setNotBefore(consumer.getJwtClaims().getNotBefore());

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

    JwsSignatureProvider noneJwsSignatureProvider = new NoneJwsSignatureProvider();
    String signed = producer.signWith(noneJwsSignatureProvider);

    SyncopeClient jwtClient = clientFactory.create(signed);
    UserSelfService jwtUserSelfService = jwtClient.getService(UserSelfService.class);
    try {
        jwtUserSelfService.read();
        fail("Failure expected on no signature");
    } catch (AccessControlException ex) {
        // expected
    }
}
 
Example 8
Source Project: syncope   Source File: JWTITCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void thirdPartyToken() throws ParseException {
    assumeFalse(SignatureAlgorithm.isPublicKeyAlgorithm(JWS_ALGORITHM));

    // Create a new 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(UUID.randomUUID().toString());
    jwtClaims.setSubject("[email protected]");
    jwtClaims.setIssuedAt(currentTime);
    jwtClaims.setIssuer(CustomJWTSSOProvider.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);

    JwsSignatureProvider customSignatureProvider =
            new HmacJwsSignatureProvider(CustomJWTSSOProvider.CUSTOM_KEY.getBytes(), JWS_ALGORITHM);
    String signed = producer.signWith(customSignatureProvider);

    SyncopeClient jwtClient = clientFactory.create(signed);

    Pair<Map<String, Set<String>>, UserTO> self = jwtClient.self();
    assertFalse(self.getLeft().isEmpty());
    assertEquals("puccini", self.getRight().getUsername());
}
 
Example 9
Source Project: syncope   Source File: JWTITCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void thirdPartyTokenUnknownUser() throws ParseException {
    assumeFalse(SignatureAlgorithm.isPublicKeyAlgorithm(JWS_ALGORITHM));

    // Create a new 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(UUID.randomUUID().toString());
    jwtClaims.setSubject("[email protected]");
    jwtClaims.setIssuedAt(currentTime);
    jwtClaims.setIssuer(CustomJWTSSOProvider.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);

    JwsSignatureProvider customSignatureProvider =
            new HmacJwsSignatureProvider(CustomJWTSSOProvider.CUSTOM_KEY.getBytes(), JWS_ALGORITHM);
    String signed = producer.signWith(customSignatureProvider);

    SyncopeClient jwtClient = clientFactory.create(signed);

    try {
        jwtClient.self();
        fail("Failure expected on an unknown subject");
    } catch (AccessControlException ex) {
        // expected
    }
}
 
Example 10
Source Project: syncope   Source File: JWTITCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void thirdPartyTokenUnknownIssuer() throws ParseException {
    assumeFalse(SignatureAlgorithm.isPublicKeyAlgorithm(JWS_ALGORITHM));

    // Create a new 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(UUID.randomUUID().toString());
    jwtClaims.setSubject("[email protected]");
    jwtClaims.setIssuedAt(currentTime);
    jwtClaims.setIssuer(CustomJWTSSOProvider.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);

    JwsSignatureProvider customSignatureProvider =
            new HmacJwsSignatureProvider(CustomJWTSSOProvider.CUSTOM_KEY.getBytes(), JWS_ALGORITHM);
    String signed = producer.signWith(customSignatureProvider);

    SyncopeClient jwtClient = clientFactory.create(signed);

    try {
        jwtClient.self();
        fail("Failure expected on an unknown issuer");
    } catch (AccessControlException ex) {
        // expected
    }
}
 
Example 11
Source Project: syncope   Source File: JWTITCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void thirdPartyTokenBadSignature() throws ParseException {
    assumeFalse(SignatureAlgorithm.isPublicKeyAlgorithm(JWS_ALGORITHM));

    // Create a new token
    Date now = new Date();

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

    JwtClaims jwtClaims = new JwtClaims();
    jwtClaims.setTokenId(UUID.randomUUID().toString());
    jwtClaims.setSubject("[email protected]");
    jwtClaims.setIssuedAt(now.getTime());
    jwtClaims.setIssuer(CustomJWTSSOProvider.ISSUER);
    jwtClaims.setExpiryTime(expiry.getTime().getTime());
    jwtClaims.setNotBefore(now.getTime());

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

    JwsSignatureProvider customSignatureProvider =
            new HmacJwsSignatureProvider((CustomJWTSSOProvider.CUSTOM_KEY + '_').getBytes(), JWS_ALGORITHM);
    String signed = producer.signWith(customSignatureProvider);

    SyncopeClient jwtClient = clientFactory.create(signed);

    try {
        jwtClient.self();
        fail("Failure expected on a bad signature");
    } catch (AccessControlException ex) {
        // expected
    }
}
 
Example 12
Source Project: cxf   Source File: JAXRSJweJwsTest.java    License: Apache License 2.0 5 votes vote down vote up
private BookStore createJweJwsBookStore(String address,
                             JwsSignatureProvider jwsSigProvider,
                             List<?> mbProviders) throws Exception {
    JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean();
    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = JAXRSJweJwsTest.class.getResource("client.xml");
    Bus springBus = bf.createBus(busFile.toString());
    bean.setBus(springBus);
    bean.setServiceClass(BookStore.class);
    bean.setAddress(address);
    List<Object> providers = new LinkedList<>();
    JweWriterInterceptor jweWriter = new JweWriterInterceptor();
    jweWriter.setUseJweOutputStream(true);
    providers.add(jweWriter);
    providers.add(new JweClientResponseFilter());
    JwsWriterInterceptor jwsWriter = new JwsWriterInterceptor();
    if (jwsSigProvider != null) {
        jwsWriter.setSignatureProvider(jwsSigProvider);
    }
    jwsWriter.setUseJwsOutputStream(true);
    providers.add(jwsWriter);
    providers.add(new JwsClientResponseFilter());
    if (mbProviders != null) {
        providers.addAll(mbProviders);
    }
    bean.setProviders(providers);
    bean.getProperties(true).put("rs.security.encryption.out.properties", SERVER_JWEJWS_PROPERTIES);
    bean.getProperties(true).put("rs.security.signature.out.properties", CLIENT_JWEJWS_PROPERTIES);
    bean.getProperties(true).put("rs.security.encryption.in.properties", CLIENT_JWEJWS_PROPERTIES);
    bean.getProperties(true).put("rs.security.signature.in.properties", SERVER_JWEJWS_PROPERTIES);
    PrivateKeyPasswordProvider provider = new PrivateKeyPasswordProviderImpl();
    bean.getProperties(true).put("rs.security.signature.key.password.provider", provider);
    bean.getProperties(true).put("rs.security.decryption.key.password.provider", provider);
    return bean.create(BookStore.class);
}
 
Example 13
Source Project: cxf   Source File: JoseClientCodeStateManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public MultivaluedMap<String, String> toRedirectState(MessageContext mc,
                                                      MultivaluedMap<String, String> requestState) {
    JweEncryptionProvider theEncryptionProvider = getInitializedEncryptionProvider();
    JwsSignatureProvider theSigProvider = getInitializedSigProvider(theEncryptionProvider);
    if (theEncryptionProvider == null && theSigProvider == null) {
        throw new OAuthServiceException("The state can not be protected");
    }
    MultivaluedMap<String, String> redirectMap = new MetadataMap<>();

    if (generateNonce && theSigProvider != null) {
        JwsCompactProducer nonceProducer = new JwsCompactProducer(OAuthUtils.generateRandomTokenKey());
        String nonceParam = nonceProducer.signWith(theSigProvider);
        requestState.putSingle(OAuthConstants.NONCE, nonceParam);
        redirectMap.putSingle(OAuthConstants.NONCE, nonceParam);
    }
    Map<String, Object> stateMap = CastUtils.cast((Map<?, ?>)requestState);
    String json = jsonp.toJson(stateMap);

    String stateParam = null;
    if (theSigProvider != null) {
        JwsCompactProducer stateProducer = new JwsCompactProducer(json);
        stateParam = stateProducer.signWith(theSigProvider);
    }

    if (theEncryptionProvider != null) {
        stateParam = theEncryptionProvider.encrypt(StringUtils.toBytesUTF8(stateParam), null);
    }
    if (storeInSession) {
        String sessionStateAttribute = OAuthUtils.generateRandomTokenKey();
        OAuthUtils.setSessionToken(mc, stateParam, sessionStateAttribute, 0);
        stateParam = sessionStateAttribute;
    }
    redirectMap.putSingle(OAuthConstants.STATE, stateParam);

    return redirectMap;
}
 
Example 14
Source Project: cxf   Source File: JoseClientCodeStateManager.java    License: Apache License 2.0 5 votes vote down vote up
protected JwsSignatureProvider getInitializedSigProvider(JweEncryptionProvider theEncryptionProvider) {
    if (sigProvider != null) {
        return sigProvider;
    }
    JwsSignatureProvider theSigProvider = JwsUtils.loadSignatureProvider(false);
    if (theSigProvider == null && theEncryptionProvider != null) {
        theSigProvider = new NoneJwsSignatureProvider();
    }
    return theSigProvider;
}
 
Example 15
Source Project: cxf   Source File: JoseSessionTokenProvider.java    License: Apache License 2.0 5 votes vote down vote up
private String protectStateString(String stateString) {
    JwsSignatureProvider jws = getInitializedSigProvider();
    JweEncryptionProvider jwe = getInitializedEncryptionProvider();
    if (jws == null && jwe == null) {
        throw new OAuthServiceException("Session token can not be created");
    }
    if (jws != null) {
        stateString = JwsUtils.sign(jws, stateString, null);
    }
    if (jwe != null) {
        stateString = jwe.encrypt(StringUtils.toBytesUTF8(stateString), null);
    }
    return stateString;
}
 
Example 16
Source Project: cxf   Source File: AbstractOAuthDataProviderTest.java    License: Apache License 2.0 5 votes vote down vote up
protected static void initializeProvider(AbstractOAuthDataProvider dataProvider) {
    dataProvider.setSupportedScopes(Collections.singletonMap("a", "A Scope"));
    dataProvider.setSupportedScopes(Collections.singletonMap("refreshToken", "RefreshToken"));

    // Configure the means of signing the issued JWT tokens
    if (dataProvider.isUseJwtFormatForAccessTokens()) {
        final JwsSignatureProvider signatureProvider =
            new PrivateKeyJwsSignatureProvider(keyPair.getPrivate(), SignatureAlgorithm.RS256);

        OAuthJoseJwtProducer jwtAccessTokenProducer = new OAuthJoseJwtProducer();
        jwtAccessTokenProducer.setSignatureProvider(signatureProvider);
        dataProvider.setJwtAccessTokenProducer(jwtAccessTokenProducer);
    }
}
 
Example 17
Source Project: cxf   Source File: JwsJsonWriterInterceptor.java    License: 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 18
Source Project: cxf   Source File: AbstractJwsMultipartSignatureFilter.java    License: 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 19
Source Project: cxf   Source File: AbstractJwsWriterProvider.java    License: 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);
}
 
Example 20
Source Project: cxf   Source File: AbstractJwsWriterProvider.java    License: Apache License 2.0 5 votes vote down vote up
protected void writeJws(JwsCompactProducer p, JwsSignatureProvider theSigProvider, OutputStream os)
    throws IOException {
    p.signWith(theSigProvider);
    JoseUtils.traceHeaders(p.getJwsHeaders());
    byte[] bytes = StringUtils.toBytesUTF8(p.getSignedEncodedJws());
    IOUtils.copy(new ByteArrayInputStream(bytes), os);
}
 
Example 21
Source Project: cxf   Source File: AbstractJwsJsonWriterProvider.java    License: 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 22
Source Project: cxf   Source File: JoseJwtProducer.java    License: Apache License 2.0 5 votes vote down vote up
public String processJwt(JwtToken jwt,
                            JweEncryptionProvider theEncProvider,
                            JwsSignatureProvider theSigProvider) {
    super.checkProcessRequirements();
    String data = null;

    if (isJweRequired() && theEncProvider == null) {
        theEncProvider = getInitializedEncryptionProvider(jwt.getJweHeaders());
        if (theEncProvider == null) {
            throw new JwtException("Unable to encrypt JWT");
        }
    }

    if (isJwsRequired()) {
        
        JwsJwtCompactProducer jws = new JwsJwtCompactProducer(jwt);
        if (jws.isPlainText()) {
            data = jws.getSignedEncodedJws();
        } else {
            if (theSigProvider == null) {
                theSigProvider = getInitializedSignatureProvider(jws.getJwsHeaders());
            }

            if (theSigProvider == null) {
                throw new JwtException("Unable to sign JWT");
            }

            data = jws.signWith(theSigProvider);
        }
        if (theEncProvider != null) {
            data = theEncProvider.encrypt(StringUtils.toBytesUTF8(data), jwt.getJweHeaders());
        }
    } else {
        JweJwtCompactProducer jwe = new JweJwtCompactProducer(jwt.getJweHeaders(), jwt.getClaims());
        data = jwe.encryptWith(theEncProvider);
    }
    return data;
}
 
Example 23
Source Project: cxf   Source File: JoseProducer.java    License: 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 24
Source Project: cxf   Source File: AbstractJoseProducer.java    License: 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 25
Source Project: cxf   Source File: AuthorizationGrantNegativeTest.java    License: Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testJWTUnauthenticatedSignature() throws Exception {
    URL busFile = AuthorizationGrantNegativeTest.class.getResource("client.xml");

    String address = "https://localhost:" + port + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());

    // Create the JWT Token
    // Create the JWT Token
    JwtClaims claims = new JwtClaims();
    claims.setSubject("consumer-id");
    claims.setIssuer("DoubleItSTSIssuer");
    Instant now = Instant.now();
    claims.setIssuedAt(now.getEpochSecond());
    claims.setExpiryTime(now.plusSeconds(60L).getEpochSecond());
    String audience = "https://localhost:" + port + "/services/token";
    claims.setAudiences(Collections.singletonList(audience));

    // Sign the JWT Token
    Properties signingProperties = new Properties();
    signingProperties.put("rs.security.keystore.type", "jks");
    signingProperties.put("rs.security.keystore.password", "security");
    signingProperties.put("rs.security.keystore.alias", "smallkey");
    signingProperties.put("rs.security.keystore.file",
        "org/apache/cxf/systest/jaxrs/security/certs/smallkeysize.jks");
    signingProperties.put("rs.security.key.password", "security");
    signingProperties.put("rs.security.signature.algorithm", "RS256");

    JwsHeaders jwsHeaders = new JwsHeaders(signingProperties);
    JwsJwtCompactProducer jws = new JwsJwtCompactProducer(jwsHeaders, claims);

    JwsSignatureProvider sigProvider =
        JwsUtils.loadSignatureProvider(signingProperties, jwsHeaders);

    String token = jws.signWith(sigProvider);

    // Get Access Token
    client.type("application/x-www-form-urlencoded").accept("application/json");
    client.path("token");

    Form form = new Form();
    form.param("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer");
    form.param("assertion", token);
    form.param("client_id", "consumer-id");
    Response response = client.post(form);

    try {
        response.readEntity(ClientAccessToken.class);
        fail("Failure expected on an unauthenticated token");
    } catch (Exception ex) {
        // expected
    }
}
 
Example 26
Source Project: cxf   Source File: OAuthUtils.java    License: Apache License 2.0 4 votes vote down vote up
public static JwsSignatureProvider getClientSecretSignatureProvider(String clientSecret) {
    Properties sigProps = JwsUtils.loadSignatureOutProperties(false);
    return JwsUtils.getHmacSignatureProvider(clientSecret,
                                             getClientSecretSignatureAlgorithm(sigProps));
}
 
Example 27
Source Project: cxf   Source File: JoseClientCodeStateManager.java    License: Apache License 2.0 4 votes vote down vote up
public void setSignatureProvider(JwsSignatureProvider signatureProvider) {
    this.sigProvider = signatureProvider;
}
 
Example 28
Source Project: cxf   Source File: JoseSessionTokenProvider.java    License: Apache License 2.0 4 votes vote down vote up
public void setJwsProvider(JwsSignatureProvider jwsProvider) {
    this.jwsProvider = jwsProvider;
}
 
Example 29
Source Project: cxf   Source File: JoseSessionTokenProvider.java    License: Apache License 2.0 4 votes vote down vote up
protected JwsSignatureProvider getInitializedSigProvider() {
    if (jwsProvider != null) {
        return jwsProvider;
    }
    return JwsUtils.loadSignatureProvider(jwsRequired);
}
 
Example 30
Source Project: cxf   Source File: OAuthJoseJwtProducer.java    License: Apache License 2.0 4 votes vote down vote up
protected JwsSignatureProvider getInitializedSignatureProvider(String clientSecret) {
    if (signWithClientSecret && !StringUtils.isEmpty(clientSecret)) {
        return OAuthUtils.getClientSecretSignatureProvider(clientSecret);
    }
    return null;
}