Browse Source

微服务之间jwt校验

yufeng0528 4 years ago
parent
commit
8326f9ee73

+ 3 - 2
spring5-auth/spring5-auth-client/src/main/java/com/yaozhitech/spring5/config/FeignOkHttpConfig.java

@@ -9,7 +9,7 @@ import org.springframework.cloud.openfeign.FeignAutoConfiguration;
9 9
 import org.springframework.context.annotation.Bean;
10 10
 import org.springframework.context.annotation.Configuration;
11 11
 
12
-import com.yaozhitech.spring5.intercept.OkHttpTokenInterceptor;
12
+import com.yaozhitech.spring5.intercept.OkHttpInterceptor;
13 13
 
14 14
 import feign.Feign;
15 15
 
@@ -19,7 +19,7 @@ import feign.Feign;
19 19
 public class FeignOkHttpConfig {
20 20
 
21 21
 	@Autowired
22
-	OkHttpTokenInterceptor okHttpLoggingInterceptor;
22
+	private OkHttpInterceptor okHttpInterceptor;
23 23
 
24 24
 	private int feignOkHttpReadTimeout = 60;
25 25
 	private int feignConnectTimeout = 60;
@@ -31,6 +31,7 @@ public class FeignOkHttpConfig {
31 31
 				.readTimeout(feignOkHttpReadTimeout, TimeUnit.SECONDS)
32 32
 				.connectTimeout(feignConnectTimeout, TimeUnit.SECONDS)
33 33
 				.writeTimeout(feignWriteTimeout, TimeUnit.SECONDS)
34
+				.addInterceptor(okHttpInterceptor)
34 35
 //				.connectionPool(new ConnectionPool())
35 36
 //				.addInterceptor(okHttpLoggingInterceptor)
36 37
 //				.addInterceptor(interceptor)

+ 53 - 0
spring5-auth/spring5-auth-client/src/main/java/com/yaozhitech/spring5/intercept/OkHttpInterceptor.java

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

+ 3 - 4
spring5-auth/spring5-auth-client/src/main/java/com/yaozhitech/spring5/intercept/OkHttpTokenInterceptor.java

@@ -1,22 +1,21 @@
1 1
 package com.yaozhitech.spring5.intercept;
2 2
 
3 3
 import org.springframework.beans.factory.annotation.Value;
4
-import org.springframework.context.annotation.Configuration;
5 4
 
6 5
 import com.yaozhitech.spring5.utils.JwtUtils;
7 6
 
8 7
 import feign.RequestInterceptor;
9 8
 import feign.RequestTemplate;
10 9
 
11
-@Configuration
12
-public class OkHttpTokenInterceptor implements RequestInterceptor{
10
+//@Configuration
11
+public class OpenFeignInterceptor implements RequestInterceptor{
13 12
 
14 13
 	@Value("${spring.application.name}")
15 14
     private String applicationName;
16 15
 	
17 16
 	@Value("${auth.client.secret}")
18 17
     private String clientSecret;
19
-
18
+	
20 19
 	@Override
21 20
 	public void apply(RequestTemplate template) {
22 21
 		template.header("x-auth-client", JwtUtils.sign(applicationName + "." + clientSecret, JwtUtils.generateSalt(), 3600));

+ 21 - 6
spring5-auth/spring5-auth-client/src/main/java/com/yaozhitech/spring5/intercept/ServiceAuthRestInterceptor.java

@@ -3,10 +3,9 @@ package com.yaozhitech.spring5.intercept;
3 3
 import javax.servlet.http.HttpServletRequest;
4 4
 import javax.servlet.http.HttpServletResponse;
5 5
 
6
-import org.slf4j.Logger;
7
-import org.slf4j.LoggerFactory;
8 6
 import org.springframework.beans.factory.annotation.Autowired;
9 7
 import org.springframework.beans.factory.annotation.Value;
8
+import org.springframework.util.StringUtils;
10 9
 import org.springframework.web.method.HandlerMethod;
11 10
 import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
12 11
 
@@ -24,7 +23,6 @@ import lombok.extern.slf4j.Slf4j;
24 23
  */
25 24
 @Slf4j
26 25
 public class ServiceAuthRestInterceptor extends HandlerInterceptorAdapter {
27
-    private Logger logger = LoggerFactory.getLogger(ServiceAuthRestInterceptor.class);
28 26
 
29 27
   @Autowired
30 28
   private AuthServerProvider clientAuthProvider;
@@ -49,12 +47,29 @@ public class ServiceAuthRestInterceptor extends HandlerInterceptorAdapter {
49 47
           return super.preHandle(request, response, handler);
50 48
       }
51 49
 
50
+		String clientToken = request.getHeader("x-auth-client-" + applicationName);
52 51
 		String client = request.getHeader("x-auth-client");
53 52
 		
54 53
 		try {
55
-			String uniqueName = JwtUtils.getUsername(client);
56
-			if (Boolean.TRUE.equals(clientAuthProvider.verify(applicationName, uniqueName.split("\\.")[0], uniqueName.split("\\.")[1]))) {
57
-				return super.preHandle(request, response, handler);
54
+			if (StringUtils.isEmpty(clientToken)) {
55
+				String clientName = JwtUtils.getUsername(client);
56
+				// authServer校验 客户端是否合法&能否有权限访问
57
+				if (Boolean.TRUE.equals(clientAuthProvider.verify(applicationName, clientName.split("\\.")[0], clientName.split("\\.")[1]))) {
58
+					// 给该客户端签名
59
+					String signToken = JwtUtils.sign(JwtUtils.generateSalt(), "xP3La8IhZjl4fmWXD.AYVH5tor5bn-Rr", 3600*12);
60
+					response.addHeader("x-auth-client-response", signToken);
61
+					
62
+					log.info("auth-server verify success, sign with {}", signToken);
63
+					
64
+					return super.preHandle(request, response, handler);
65
+				}
66
+				
67
+			} else {
68
+				// jwt校验
69
+				if (!JwtUtils.isTokenExpired(clientToken) && JwtUtils.verifyToken(clientToken, "xP3La8IhZjl4fmWXD.AYVH5tor5bn-Rr") != null) {
70
+					log.info("local service jwt verify success");
71
+					return super.preHandle(request, response, handler);
72
+				}
58 73
 			}
59 74
 			
60 75
 		} catch (Exception e) {

+ 6 - 0
spring5-order/src/main/resources/bootstrap.yml

@@ -10,3 +10,9 @@ spring:
10 10
       config:
11 11
         server-addr: ${REGISTER_HOST:192.168.99.100}:${REGISTER_PORT:8848}
12 12
         file-extension: yml
13
+        
14
+feign:
15
+   httpclient:
16
+      enabled: false
17
+   okhttp:
18
+      enabled: true