Advertisement
Guest User

Untitled

a guest
Dec 6th, 2019
261
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.20 KB | None | 0 0
  1. package com.example.demo.wykop;
  2.  
  3. import com.fasterxml.jackson.databind.JsonNode;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import org.springframework.http.HttpRequest;
  6. import org.springframework.http.client.ClientHttpRequestExecution;
  7. import org.springframework.http.client.ClientHttpRequestInterceptor;
  8. import org.springframework.http.client.ClientHttpResponse;
  9.  
  10. import java.io.IOException;
  11. import java.math.BigInteger;
  12. import java.security.MessageDigest;
  13. import java.security.NoSuchAlgorithmException;
  14. import java.util.Objects;
  15. import java.util.stream.StreamSupport;
  16.  
  17. import static java.util.stream.Collectors.joining;
  18.  
  19. public class WykopApiSigningInterceptor implements ClientHttpRequestInterceptor {
  20.  
  21.     private static final String API_SIGN_HEADER = "apisign";
  22.  
  23.     private final ObjectMapper objectMapper;
  24.     private final String secret;
  25.  
  26.     public WykopApiSigningInterceptor(ObjectMapper objectMapper, String secret) {
  27.         this.objectMapper = objectMapper;
  28.         this.secret = secret;
  29.     }
  30.  
  31.     @Override
  32.     public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
  33.         var url = request.getURI().toASCIIString();
  34.         var paramValues = extractParamValues(objectMapper.readTree(body));
  35.         signRequest(request, secret, url, paramValues);
  36.         return execution.execute(request, body);
  37.     }
  38.  
  39.     private static void signRequest(HttpRequest request, String secret, String url, String paramValues) {
  40.         try {
  41.             MessageDigest md = MessageDigest.getInstance("MD5");
  42.             md.update((secret + url + paramValues).getBytes());
  43.             System.out.println(secret);
  44.             var md5Sum = String.format("%032x", new BigInteger(1, md.digest()));
  45.             request.getHeaders().add(API_SIGN_HEADER, md5Sum);
  46.         } catch (NoSuchAlgorithmException e) {
  47.             throw new RuntimeException(e);
  48.         }
  49.     }
  50.  
  51.     private static String extractParamValues(JsonNode body) {
  52.         return StreamSupport.stream(body.spliterator(), false)
  53.                 .map(JsonNode::textValue)
  54.                 .filter(Objects::nonNull)
  55.                 .collect(joining(","));
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement