OkHttpInterceptor.java 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package com.yaozhitech.spring5.intercept;
  2. import java.io.IOException;
  3. import java.util.Map;
  4. import java.util.concurrent.ConcurrentHashMap;
  5. import org.springframework.beans.factory.annotation.Value;
  6. import org.springframework.stereotype.Component;
  7. import com.yaozhitech.spring5.utils.JwtUtils;
  8. import lombok.extern.slf4j.Slf4j;
  9. import okhttp3.Interceptor;
  10. import okhttp3.Request;
  11. import okhttp3.Response;
  12. @Component
  13. @Slf4j
  14. public class OkHttpInterceptor implements Interceptor{
  15. @Value("${spring.application.name}")
  16. private String applicationName;
  17. @Value("${auth.client.secret}")
  18. private String clientSecret;
  19. private Map<String, String> headerMap = new ConcurrentHashMap<String, String>();
  20. @Override
  21. public Response intercept(Chain chain) throws IOException {
  22. Request request = chain.request();
  23. String path = request.url().pathSegments().get(0);
  24. if (headerMap.containsKey(path)) {
  25. log.info("request {} header {} ", "x-auth-client-" + path, headerMap.get(path));
  26. request = request.newBuilder().addHeader("x-auth-client-" + path, headerMap.get(path)).build();
  27. } else {
  28. String token = JwtUtils.sign(applicationName + "." + clientSecret, JwtUtils.generateSalt(), 3600);
  29. log.info("request {} header {} ", "x-auth-client", token);
  30. request = request.newBuilder().addHeader("x-auth-client", token).build();
  31. }
  32. Response response = chain.proceed(request);
  33. String authClientResponse = response.header("x-auth-client-response");
  34. if (authClientResponse != null) {
  35. headerMap.put(path, authClientResponse);
  36. }
  37. return response;
  38. }
  39. }