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

The following examples show how to use org.apache.cxf.rs.security.jose.jws.JwsSignatureProvider. 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: 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 #2
Source File: TestJwts.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
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 #3
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 #4
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 #5
Source File: JoseJwtProducer.java    From cxf with 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 #6
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 #7
Source File: AbstractJwsWriterProvider.java    From cxf with 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 #8
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);
}
 
Example #9
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 #10
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 #11
Source File: AbstractOAuthDataProviderTest.java    From cxf with 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 #12
Source File: JoseSessionTokenProvider.java    From cxf with 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 #13
Source File: JoseClientCodeStateManager.java    From cxf with 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 #14
Source File: JoseClientCodeStateManager.java    From cxf with 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 #15
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 #16
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 #17
Source File: JAXRSJweJwsTest.java    From cxf with 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 #18
Source File: DefaultJoseImpl.java    From thorntail with 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 #19
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 #20
Source File: JWTITCase.java    From syncope with 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 #21
Source File: JWTITCase.java    From syncope with 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 #22
Source File: JWTITCase.java    From syncope with 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 #23
Source File: JWTITCase.java    From syncope with 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 #24
Source File: JWTITCase.java    From syncope with 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 #25
Source File: JwsWriterInterceptor.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Override
public void aroundWriteTo(WriterInterceptorContext ctx) throws IOException, WebApplicationException {
    if (ctx.getEntity() == null) {
        ctx.proceed();
        return;
    }
    JwsHeaders headers = new JwsHeaders();
    JwsSignatureProvider sigProvider = getInitializedSigProvider(headers);
    setContentTypeIfNeeded(headers, ctx);
    if (!encodePayload) {
        headers.setPayloadEncodingStatus(false);
    }
    protectHttpHeadersIfNeeded(ctx, headers);
    OutputStream actualOs = ctx.getOutputStream();
    if (useJwsOutputStream) {
        JwsSignature jwsSignature = sigProvider.createJwsSignature(headers);
        JoseUtils.traceHeaders(headers);
        JwsOutputStream jwsStream = new JwsOutputStream(actualOs, jwsSignature, true);
        byte[] headerBytes = StringUtils.toBytesUTF8(writer.toJson(headers));
        Base64UrlUtility.encodeAndStream(headerBytes, 0, headerBytes.length, jwsStream);
        jwsStream.write(new byte[]{'.'});

        Base64UrlOutputStream base64Stream = null;
        if (encodePayload) {
            base64Stream = new Base64UrlOutputStream(jwsStream);
            ctx.setOutputStream(base64Stream);
        } else {
            ctx.setOutputStream(jwsStream);
        }
        ctx.proceed();
        setJoseMediaType(ctx);
        if (base64Stream != null) {
            base64Stream.flush();
        }
        jwsStream.flush();
    } else {
        CachedOutputStream cos = new CachedOutputStream();
        ctx.setOutputStream(cos);
        ctx.proceed();
        JwsCompactProducer p = new JwsCompactProducer(headers, new String(cos.getBytes(), StandardCharsets.UTF_8));
        setJoseMediaType(ctx);
        writeJws(p, sigProvider, actualOs);
    }
}
 
Example #26
Source File: ApacheCXFProducer.java    From cxf with Apache License 2.0 4 votes vote down vote up
private void produceJsonJWS(String plainText, JsonWebKey key, JwsHeaders jwsHeaders, boolean flattened) {
    JwsJsonProducer jwsProducer = new JwsJsonProducer(plainText, flattened);
    JwsSignatureProvider jwsSignatureProvider = JwsUtils.getSignatureProvider(key,
        jwsHeaders.getSignatureAlgorithm());
    jwsProducer.signWith(jwsSignatureProvider, null, jwsHeaders);
}
 
Example #27
Source File: AbstractJoseProducer.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void setSignatureProvider(JwsSignatureProvider signatureProvider) {
    this.sigProvider = signatureProvider;
}
 
Example #28
Source File: AbstractJwsJsonWriterProvider.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void setSignatureProviders(List<JwsSignatureProvider> signatureProviders) {
    this.sigProviders = signatureProviders;
}
 
Example #29
Source File: AbstractJwsJsonWriterProvider.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void setSignatureProvider(JwsSignatureProvider signatureProvider) {
    setSignatureProviders(Collections.singletonList(signatureProvider));
}
 
Example #30
Source File: AbstractJwsWriterProvider.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void setSignatureProvider(JwsSignatureProvider signatureProvider) {
    this.sigProvider = signatureProvider;
}