123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- package com.yaozhitech.spring5.intercept;
- import java.io.IOException;
- import java.util.Map;
- import java.util.concurrent.ConcurrentHashMap;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.stereotype.Component;
- import com.yaozhitech.spring5.utils.JwtUtils;
- import lombok.extern.slf4j.Slf4j;
- import okhttp3.Interceptor;
- import okhttp3.Request;
- import okhttp3.Response;
- @Component
- @Slf4j
- public class OkHttpInterceptor implements Interceptor{
-
- @Value("${spring.application.name}")
- private String applicationName;
-
- @Value("${auth.client.secret}")
- private String clientSecret;
-
- private Map<String, String> headerMap = new ConcurrentHashMap<String, String>();
- @Override
- public Response intercept(Chain chain) throws IOException {
- Request request = chain.request();
- String path = request.url().pathSegments().get(0);
-
- if (headerMap.containsKey(path)) {
- log.info("request {} header {} ", "x-auth-client-" + path, headerMap.get(path));
- request = request.newBuilder().addHeader("x-auth-client-" + path, headerMap.get(path)).build();
- } else {
- String token = JwtUtils.sign(applicationName + "." + clientSecret, JwtUtils.generateSalt(), 3600);
- log.info("request {} header {} ", "x-auth-client", token);
- request = request.newBuilder().addHeader("x-auth-client", token).build();
- }
-
- Response response = chain.proceed(request);
- String authClientResponse = response.header("x-auth-client-response");
-
- if (authClientResponse != null) {
- headerMap.put(path, authClientResponse);
- }
-
- return response;
- }
- }
|