use of org.apache.cxf.rs.security.jose.jws.JwsJsonOutputStream in project cxf by apache.
the class JwsJsonWriterInterceptor method aroundWriteTo.
@Override
public void aroundWriteTo(WriterInterceptorContext ctx) throws IOException, WebApplicationException {
if (ctx.getEntity() == null) {
ctx.proceed();
return;
}
List<String> propLocs = getPropertyLocations();
List<JwsHeaders> protectedHeaders = new ArrayList<>(propLocs.size());
for (int i = 0; i < propLocs.size(); i++) {
protectedHeaders.add(new JwsHeaders());
}
List<JwsSignatureProvider> sigProviders = getInitializedSigProviders(propLocs, protectedHeaders);
OutputStream actualOs = ctx.getOutputStream();
if (useJwsOutputStream) {
List<String> encodedProtectedHeaders = new ArrayList<>(sigProviders.size());
List<JwsSignature> signatures = new ArrayList<>(sigProviders.size());
int size = sigProviders.size();
for (int i = 0; i < size; i++) {
JwsSignatureProvider signer = sigProviders.get(i);
JwsHeaders protectedHeader = protectedHeaders.get(i);
prepareProtectedHeader(protectedHeader, ctx, signer, size == 1);
String encoded = Base64UrlUtility.encode(writer.toJson(protectedHeader));
encodedProtectedHeaders.add(encoded);
JwsSignature signature = signer.createJwsSignature(protectedHeader);
byte[] start = StringUtils.toBytesUTF8(encoded + ".");
signature.update(start, 0, start.length);
signatures.add(signature);
}
ctx.setMediaType(JAXRSUtils.toMediaType(JoseConstants.MEDIA_TYPE_JOSE_JSON));
actualOs.write(StringUtils.toBytesUTF8("{\"payload\":\""));
JwsJsonOutputStream jwsStream = new JwsJsonOutputStream(actualOs, encodedProtectedHeaders, signatures);
Base64UrlOutputStream base64Stream = null;
if (encodePayload) {
base64Stream = new Base64UrlOutputStream(jwsStream);
ctx.setOutputStream(base64Stream);
} else {
ctx.setOutputStream(jwsStream);
}
ctx.proceed();
if (base64Stream != null) {
base64Stream.flush();
}
jwsStream.flush();
} else {
CachedOutputStream cos = new CachedOutputStream();
ctx.setOutputStream(cos);
ctx.proceed();
JwsJsonProducer p = new JwsJsonProducer(new String(cos.getBytes(), StandardCharsets.UTF_8));
int size = sigProviders.size();
for (int i = 0; i < size; i++) {
JwsSignatureProvider signer = sigProviders.get(i);
JwsHeaders protectedHeader = protectedHeaders.get(i);
prepareProtectedHeader(protectedHeader, ctx, signer, size == 1);
p.signWith(signer, protectedHeader, null);
}
ctx.setMediaType(JAXRSUtils.toMediaType(JoseConstants.MEDIA_TYPE_JOSE_JSON));
writeJws(p, actualOs);
}
}
Aggregations