Browse Source

用户token

YeLuo 5 years ago
parent
commit
5c90e33dae

+ 16 - 1
pom.xml

@@ -73,6 +73,11 @@
73 73
 			<artifactId>mysql-connector-java</artifactId>
74 74
 			<scope>runtime</scope>
75 75
 		</dependency>
76
+		<!-- redis -->
77
+		<dependency>
78
+			<groupId>org.springframework.boot</groupId>
79
+			<artifactId>spring-boot-starter-data-redis</artifactId>
80
+		</dependency>
76 81
 		<!-- lombok -->
77 82
 		<dependency>
78 83
 			<groupId>org.projectlombok</groupId>
@@ -94,6 +99,11 @@
94 99
 		<!-- commons -->
95 100
 		<dependency>
96 101
 			<groupId>org.apache.commons</groupId>
102
+			<artifactId>commons-io</artifactId>
103
+			<version>1.3.2</version>
104
+		</dependency>
105
+		<dependency>
106
+			<groupId>org.apache.commons</groupId>
97 107
 			<artifactId>commons-lang3</artifactId>
98 108
 			<version>3.4</version>
99 109
 		</dependency>
@@ -109,7 +119,12 @@
109 119
 			<groupId>org.apache.httpcomponents</groupId>
110 120
 			<artifactId>httpmime</artifactId>
111 121
 		</dependency>
112
-
122
+		<!-- json -->
123
+		<dependency>
124
+			<groupId>com.alibaba</groupId>
125
+			<artifactId>fastjson</artifactId>
126
+			<version>1.2.45</version>
127
+		</dependency>
113 128
 	</dependencies>
114 129
 
115 130
 	<build>

+ 3 - 1
src/main/java/com/yingying/tourist/business/BusinessConstant.java

@@ -5,6 +5,8 @@ import java.util.Map;
5 5
 
6 6
 public class BusinessConstant {
7 7
 
8
+    public static final String COOKIEDOMAIN = "tourist.jituan.com";
9
+
8 10
     public enum Identity{
9 11
         A("A","自然的崇拜者"), B("B","洒脱的冒险家"), C("C","文化的朝圣者"),D("D","心灵的按摩师");
10 12
 
@@ -26,7 +28,7 @@ public class BusinessConstant {
26 28
         }
27 29
     }
28 30
 
29
-    public static Map<Integer, String> describeMap = new HashMap<>(16);
31
+    public static Map<Integer, String> describeMap = new HashMap<>(16,1);
30 32
     static {
31 33
         describeMap.put(1,"在山西挖煤挖到300000斤");
32 34
         describeMap.put(2,"做环卫工打扫400个公厕坑位");

+ 117 - 0
src/main/java/com/yingying/tourist/common/UrlUtils.java

@@ -0,0 +1,117 @@
1
+package com.yingying.tourist.common;
2
+
3
+import org.apache.http.NameValuePair;
4
+import org.apache.http.client.entity.UrlEncodedFormEntity;
5
+import org.apache.http.message.BasicNameValuePair;
6
+import org.apache.http.util.EntityUtils;
7
+
8
+import javax.servlet.http.HttpServletRequest;
9
+import java.io.BufferedReader;
10
+import java.io.IOException;
11
+import java.util.ArrayList;
12
+import java.util.Enumeration;
13
+import java.util.List;
14
+import java.util.Map;
15
+import java.util.Map.Entry;
16
+
17
+
18
+public class UrlUtils {
19
+
20
+	public static String buildUrlNormal(String url,Map<String,String> params) throws Exception{
21
+		try {
22
+			StringBuilder sb = new StringBuilder();
23
+			sb.append(url);
24
+			if (params != null && !params.isEmpty()) {
25
+				sb.append("?");
26
+				for (Entry<String, String> entry : params.entrySet()) {
27
+					String key = entry.getKey();
28
+					String value = entry.getValue();
29
+					sb.append(key);
30
+					sb.append("=");
31
+					sb.append(value);
32
+					sb.append("&");
33
+				}
34
+			}
35
+			return sb.toString();
36
+		}catch (Exception e) {
37
+			e.printStackTrace();
38
+			throw e;
39
+		}
40
+	}
41
+	
42
+	public static String buildUrl(String url,Map<String,String> params) throws Exception{
43
+		try {
44
+			StringBuilder sb = new StringBuilder();
45
+			sb.append(url);
46
+			if (params != null && !params.isEmpty()) {
47
+				sb.append("?");
48
+				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
49
+				for (Entry<String, String> entry : params.entrySet()) {
50
+					String key = entry.getKey();
51
+					String value = entry.getValue();
52
+					nameValuePairs.add(new BasicNameValuePair(key, value));
53
+				}
54
+				sb.append(EntityUtils.toString(new UrlEncodedFormEntity(
55
+						nameValuePairs)));
56
+			}
57
+			return sb.toString();
58
+		}catch (Exception e) {
59
+			e.printStackTrace();
60
+			throw e;
61
+		}
62
+	}
63
+	
64
+	public static String buildParams(Map<String,String> params) throws Exception{
65
+		try {
66
+			if (params != null && !params.isEmpty()) {
67
+				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
68
+				for (Entry<String, String> entry : params.entrySet()) {
69
+					String key = entry.getKey();
70
+					String value = entry.getValue();
71
+					nameValuePairs.add(new BasicNameValuePair(key, value));
72
+				}
73
+				return EntityUtils.toString(new UrlEncodedFormEntity(
74
+						nameValuePairs));
75
+			}
76
+			return "";
77
+		}catch (Exception e) {
78
+			e.printStackTrace();
79
+			throw e;
80
+		}
81
+	}
82
+	
83
+	public static String getRequestPayload(HttpServletRequest req) {
84
+		StringBuilder sb = new StringBuilder();
85
+		if (req.getContentType() != null && req.getContentType().contains("application/json")) {
86
+			try {
87
+				BufferedReader reader = req.getReader();
88
+				char[] buff = new char[1024];
89
+				int len;
90
+				while ((len = reader.read(buff)) != -1) {
91
+					sb.append(buff, 0, len);
92
+				}
93
+			} catch (IOException e) {
94
+				e.printStackTrace();
95
+			}
96
+		}
97
+		return sb.toString();
98
+	}
99
+	
100
+	@SuppressWarnings("rawtypes")
101
+	public static String getRequestParams(HttpServletRequest req) {
102
+		StringBuilder sb = new StringBuilder();
103
+		Enumeration parameterNames = req.getParameterNames();
104
+		while (parameterNames.hasMoreElements()) {
105
+			String name = (String) parameterNames.nextElement();
106
+			String[] values = req.getParameterValues(name);
107
+			sb.append(name).append("=");
108
+			if (values != null) {
109
+				for (String v : values) {
110
+					sb.append(v).append("&");
111
+				}
112
+			}
113
+		}
114
+		return sb.toString();
115
+	}
116
+	
117
+}

+ 97 - 0
src/main/java/com/yingying/tourist/request/HttpServletRequestReplacedFilter.java

@@ -0,0 +1,97 @@
1
+package com.yingying.tourist.request;
2
+
3
+import org.apache.commons.io.IOUtils;
4
+import org.springframework.core.annotation.Order;
5
+import org.springframework.stereotype.Component;
6
+
7
+import javax.servlet.*;
8
+import javax.servlet.annotation.WebFilter;
9
+import javax.servlet.http.HttpServletRequest;
10
+import javax.servlet.http.HttpServletRequestWrapper;
11
+import java.io.BufferedReader;
12
+import java.io.ByteArrayInputStream;
13
+import java.io.IOException;
14
+import java.io.InputStreamReader;
15
+
16
+
17
+/**
18
+ * request.getInputStream()/getReader 只能获取一次的问题
19
+ * 
20
+ * @author sks
21
+ *
22
+ */
23
+@Component
24
+@Order(1)
25
+@WebFilter(filterName = "HttpServletRequestReplacedFilter", urlPatterns = "/*")
26
+public class HttpServletRequestReplacedFilter implements Filter {
27
+
28
+	@Override
29
+	public void destroy() {
30
+		// TODO Auto-generated method stub
31
+
32
+	}
33
+
34
+	@Override
35
+	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
36
+		ServletRequest requestWrapper = null;
37
+		if (request instanceof HttpServletRequest) {
38
+			String contentType = request.getContentType();
39
+			if (contentType != null && contentType.contains("application/json")) {
40
+				requestWrapper = new BodyReaderHttpServletRequestWrapper((HttpServletRequest) request);
41
+			}
42
+		}
43
+		if (null == requestWrapper) {
44
+			chain.doFilter(request, response);
45
+		} else {
46
+			chain.doFilter(requestWrapper, response);
47
+		}
48
+	}
49
+
50
+	@Override
51
+	public void init(FilterConfig arg0) throws ServletException {
52
+		// TODO Auto-generated method stub
53
+
54
+	}
55
+
56
+	private class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper {
57
+		private final byte[] rawData;
58
+
59
+		public BodyReaderHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
60
+			super(request);
61
+			rawData = IOUtils.toByteArray(request.getReader());
62
+		}
63
+
64
+		@Override
65
+		public BufferedReader getReader() throws IOException {
66
+			return new BufferedReader(new InputStreamReader(getInputStream()));
67
+		}
68
+
69
+		@Override
70
+		public ServletInputStream getInputStream() throws IOException {
71
+			final ByteArrayInputStream bais = new ByteArrayInputStream(rawData);
72
+			return new ServletInputStream() {
73
+
74
+				@Override
75
+				public int read() throws IOException {
76
+					return bais.read();
77
+				}
78
+
79
+				@Override
80
+				public boolean isFinished() {
81
+					return bais.available() == 0;
82
+				}
83
+
84
+				@Override
85
+				public boolean isReady() {
86
+					return true;
87
+				}
88
+
89
+				@Override
90
+				public void setReadListener(ReadListener arg0) {
91
+					throw new RuntimeException("Not implemented");
92
+				}
93
+			};
94
+		}
95
+	}
96
+
97
+}

+ 18 - 0
src/main/java/com/yingying/tourist/request/RequestSessionKey.java

@@ -0,0 +1,18 @@
1
+package com.yingying.tourist.request;
2
+
3
+public class RequestSessionKey {
4
+	private static ThreadLocal<String> sessionKeyHolder = new ThreadLocal<>();
5
+	
6
+	public static void putSessionKey(String sessionKey) {
7
+		sessionKeyHolder.set(sessionKey);
8
+	}
9
+	
10
+	public static String getSessionKey() {
11
+		return sessionKeyHolder.get();
12
+	}
13
+	
14
+	public static void removeKey() {
15
+		sessionKeyHolder.remove();
16
+	}
17
+	
18
+}

+ 43 - 0
src/main/java/com/yingying/tourist/request/SessionAuthorization.java

@@ -0,0 +1,43 @@
1
+package com.yingying.tourist.request;
2
+
3
+import org.springframework.beans.factory.InitializingBean;
4
+import org.springframework.beans.factory.annotation.Autowired;
5
+import org.springframework.data.redis.core.RedisTemplate;
6
+import org.springframework.data.redis.core.ValueOperations;
7
+import org.springframework.stereotype.Component;
8
+
9
+import java.util.concurrent.TimeUnit;
10
+
11
+@Component
12
+public class SessionAuthorization implements InitializingBean {
13
+	public static final String SESSION_KEY_COOKIE_NAME = "jituan";
14
+	public static final int DEFAULT_SESSION_COOKIE_EXPIRE = 604800; // 604800 604800
15
+	public static final String SESSION_KEY_PREFIX = "WeChatToken";
16
+	
17
+	@Autowired
18
+	private RedisTemplate<Object, Object> redisTemplate;
19
+	
20
+	private static RedisTemplate<Object, Object> baseRedisTemplate;
21
+	
22
+	public static void setSession(String token) {
23
+		ValueOperations<Object, Object> ops = baseRedisTemplate.opsForValue();
24
+		ops.set(SESSION_KEY_PREFIX + ":" + RequestSessionKey.getSessionKey(), token, DEFAULT_SESSION_COOKIE_EXPIRE, TimeUnit.SECONDS);
25
+	}
26
+	
27
+	public static Integer getSession() {
28
+		ValueOperations<Object, Object> ops = baseRedisTemplate.opsForValue();
29
+		Integer sessionValue = (Integer) ops.get(SESSION_KEY_PREFIX + ":" + RequestSessionKey.getSessionKey());
30
+		
31
+		return sessionValue;
32
+	}
33
+	
34
+	public static void removeSession() {
35
+		baseRedisTemplate.delete(SESSION_KEY_PREFIX + ":" + RequestSessionKey.getSessionKey());
36
+	}
37
+	
38
+	@Override
39
+	public void afterPropertiesSet() throws Exception {
40
+		baseRedisTemplate = this.redisTemplate;
41
+	}
42
+	
43
+}

+ 76 - 0
src/main/java/com/yingying/tourist/request/SessionFilter.java

@@ -0,0 +1,76 @@
1
+package com.yingying.tourist.request;
2
+
3
+import com.alibaba.fastjson.JSONObject;
4
+import com.yingying.tourist.business.BusinessConstant;
5
+import com.yingying.tourist.common.UrlUtils;
6
+import lombok.extern.slf4j.Slf4j;
7
+import org.apache.commons.lang3.StringUtils;
8
+import org.springframework.core.annotation.Order;
9
+import org.springframework.stereotype.Component;
10
+import org.springframework.web.util.WebUtils;
11
+
12
+import javax.servlet.*;
13
+import javax.servlet.annotation.WebFilter;
14
+import javax.servlet.http.Cookie;
15
+import javax.servlet.http.HttpServletRequest;
16
+import javax.servlet.http.HttpServletResponse;
17
+import java.io.IOException;
18
+import java.util.UUID;
19
+
20
+@Component
21
+@Order(2)
22
+@WebFilter(filterName = "SessionFilter", urlPatterns = "/*")
23
+@Slf4j
24
+public class SessionFilter implements Filter {
25
+	
26
+	
27
+	@Override
28
+	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
29
+		// 检查sessionId的cookie是否存在,不存在即为新连接,需要初始化sessionId到cookie中
30
+		checkRemoteSession((HttpServletRequest) request, (HttpServletResponse) response);
31
+		chain.doFilter(request, response);
32
+	}
33
+
34
+	@Override
35
+	public void destroy() {
36
+	}
37
+
38
+	@Override
39
+	public void init(FilterConfig filterConfig) throws ServletException {
40
+		
41
+	}
42
+
43
+	private void checkRemoteSession(HttpServletRequest request, HttpServletResponse response) {
44
+		String sessionKey = null;
45
+		String token = request.getParameter("token");
46
+		log.info("token------>>>first:[{}]",token);
47
+        if (StringUtils.isEmpty(token)) {
48
+            String payload = UrlUtils.getRequestPayload(request);
49
+            if (!StringUtils.isEmpty(payload)) {
50
+                JSONObject jsonObject = JSONObject.parseObject(payload);
51
+                token = jsonObject.getString("token");
52
+            }
53
+        }
54
+		
55
+		if (StringUtils.isNotEmpty(token)) {
56
+			sessionKey = token;
57
+			log.info("sessionKey------>>>second:[{}]",sessionKey);
58
+		} else {
59
+			Cookie sessionKeyCookie = WebUtils.getCookie(request, SessionAuthorization.SESSION_KEY_COOKIE_NAME);
60
+			if (sessionKeyCookie == null) {
61
+				sessionKey = UUID.randomUUID().toString();
62
+				sessionKeyCookie = new Cookie(SessionAuthorization.SESSION_KEY_COOKIE_NAME, sessionKey);
63
+			} else {
64
+				sessionKey = sessionKeyCookie.getValue();
65
+			}
66
+			log.info("sessionKey------>>>third:[{}]",sessionKey);
67
+			sessionKeyCookie.setPath("/");
68
+			sessionKeyCookie.setDomain(BusinessConstant.COOKIEDOMAIN);
69
+			sessionKeyCookie.setMaxAge(SessionAuthorization.DEFAULT_SESSION_COOKIE_EXPIRE);
70
+			sessionKeyCookie.setHttpOnly(true);
71
+			response.addCookie(sessionKeyCookie);
72
+		}
73
+		RequestSessionKey.putSessionKey(sessionKey);
74
+	}
75
+	
76
+}