Skip to content

Commit d39306c

Browse files
committed
fix:解决jwt刷新没有写入到Cookie的问题
1 parent d3fc9ce commit d39306c

File tree

6 files changed

+96
-47
lines changed

6 files changed

+96
-47
lines changed

mogu_admin/src/main/java/com/moxi/mogublog/admin/AdminApplication.java

Lines changed: 33 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,17 @@
99
import org.springframework.context.annotation.Bean;
1010
import org.springframework.context.annotation.ComponentScan;
1111
import org.springframework.transaction.annotation.EnableTransactionManagement;
12+
import org.springframework.web.context.request.RequestContextHolder;
13+
import org.springframework.web.context.request.ServletRequestAttributes;
1214
import org.springframework.web.cors.CorsConfiguration;
1315
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
1416
import org.springframework.web.filter.CorsFilter;
17+
import org.springframework.web.servlet.config.annotation.CorsRegistry;
18+
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
1519
import springfox.documentation.swagger2.annotations.EnableSwagger2;
1620

1721
import javax.annotation.PostConstruct;
22+
import javax.servlet.http.HttpServletRequest;
1823
import java.util.TimeZone;
1924

2025
@EnableTransactionManagement
@@ -42,13 +47,13 @@ public static void main(String[] args) {
4247
SpringApplication.run(AdminApplication.class, args);
4348
}
4449

45-
private CorsConfiguration buildConfig() {
46-
CorsConfiguration corsConfiguration = new CorsConfiguration();
47-
corsConfiguration.addAllowedOrigin("*");
48-
corsConfiguration.addAllowedHeader("*");
49-
corsConfiguration.addAllowedMethod("*");
50-
return corsConfiguration;
51-
}
50+
// private CorsConfiguration buildConfig() {
51+
// CorsConfiguration corsConfiguration = new CorsConfiguration();
52+
// corsConfiguration.addAllowedOrigin("localhost");
53+
// corsConfiguration.addAllowedHeader("*");
54+
// corsConfiguration.addAllowedMethod("*");
55+
// return corsConfiguration;
56+
// }
5257

5358
/**
5459
* 设置时区
@@ -63,11 +68,28 @@ void setDefaultTimezone() {
6368
*
6469
* @return
6570
*/
71+
// @Bean
72+
// public CorsFilter corsFilter() {
73+
// UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
74+
// source.registerCorsConfiguration("/**", buildConfig());
75+
// return new CorsFilter(source);
76+
// }
77+
6678
@Bean
67-
public CorsFilter corsFilter() {
68-
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
69-
source.registerCorsConfiguration("/**", buildConfig());
70-
return new CorsFilter(source);
79+
public WebMvcConfigurer corsConfigurer() {
80+
return new WebMvcConfigurer() {
81+
@Override
82+
public void addCorsMappings(CorsRegistry registry) {
83+
//配置允许跨域访问的路径
84+
registry.addMapping("/**/**")
85+
.allowedOrigins("*")
86+
.allowedMethods("*")
87+
.allowedHeaders("*")
88+
.allowCredentials(true)
89+
.exposedHeaders("")
90+
.maxAge(3600);
91+
}
92+
};
7193
}
7294

7395
}

mogu_admin/src/main/java/com/moxi/mogublog/admin/security/JwtAuthenticationTokenFilter.java

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
import com.moxi.mogublog.admin.global.SysConf;
55
import com.moxi.mogublog.config.jwt.Audience;
66
import com.moxi.mogublog.config.jwt.JwtHelper;
7+
import com.moxi.mogublog.utils.CookieUtils;
8+
import com.moxi.mogublog.utils.DateUtils;
79
import com.moxi.mogublog.utils.RedisUtil;
810
import com.moxi.mogublog.utils.StringUtils;
911
import lombok.extern.slf4j.Slf4j;
@@ -22,6 +24,7 @@
2224
import javax.servlet.http.HttpServletRequest;
2325
import javax.servlet.http.HttpServletResponse;
2426
import java.io.IOException;
27+
import java.util.Date;
2528
import java.util.concurrent.TimeUnit;
2629

2730
@Slf4j
@@ -74,10 +77,25 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
7477

7578
// 获取在线的管理员信息
7679
String onlineAdmin = redisUtil.get(RedisConf.LOGIN_TOKEN_KEY + RedisConf.SEGMENTATION + authHeader);
80+
7781
if(StringUtils.isNotEmpty(onlineAdmin) && !jwtHelper.isExpiration(token, audience.getBase64Secret())) {
78-
// 重新更新过期时间
79-
redisUtil.setEx(RedisConf.LOGIN_TOKEN_KEY + RedisConf.SEGMENTATION + authHeader, onlineAdmin, 30, TimeUnit.MINUTES);
80-
jwtHelper.refreshToken(token, audience.getBase64Secret(), expiresSecond);
82+
/**
83+
* 得到过期时间
84+
*/
85+
Date expirationDate = jwtHelper.getExpiration(token, audience.getBase64Secret());
86+
long nowMillis = System.currentTimeMillis();
87+
Date nowDate = new Date(nowMillis);
88+
// 得到两个日期相差的间隔
89+
Integer minute = DateUtils.getMinuteByTwoDay(expirationDate, nowDate);
90+
// 如果小于5分钟,那么更新过期时间
91+
if(minute < 5) {
92+
// 生成一个新的Token
93+
String newToken = tokenHead + jwtHelper.refreshToken(token, audience.getBase64Secret(), expiresSecond * 1000);
94+
// 生成新的token,发送到客户端
95+
CookieUtils.setCookie("Admin-Token", newToken, expiresSecond.intValue());
96+
// 重新更新Redis中的过期时间
97+
redisUtil.setEx(RedisConf.LOGIN_TOKEN_KEY + RedisConf.SEGMENTATION + newToken, onlineAdmin, expiresSecond, TimeUnit.SECONDS);
98+
}
8199
} else {
82100
chain.doFilter(request, response);
83101
return;

mogu_admin/src/main/resources/application.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -172,11 +172,11 @@ mybatis-plus:
172172
cache-enabled: false
173173

174174
##jwt配置
175-
tokenHead: bearer;
175+
tokenHead: bearer_
176176
tokenHeader: Authorization
177177
isRememberMeExpiresSecond: 259200 #记住账号为3天有效
178178
audience:
179179
clientId: 098f6bcd4621d373cade4e832627b4f6
180180
base64Secret: MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY=
181181
name: mogublog
182-
expiresSecond: 3600 #1个小时 3600
182+
expiresSecond: 660 #1个小时 3600

mogu_utils/src/main/java/com/moxi/mogublog/utils/CookieUtils.java

Lines changed: 21 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
package com.moxi.mogublog.utils;
22

3+
import org.springframework.web.context.request.RequestContextHolder;
4+
import org.springframework.web.context.request.ServletRequestAttributes;
5+
36
import javax.servlet.http.Cookie;
47
import javax.servlet.http.HttpServletRequest;
58
import javax.servlet.http.HttpServletResponse;
@@ -83,67 +86,58 @@ public static String getCookieValue(HttpServletRequest request, String cookieNam
8386
/**
8487
* 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码
8588
*/
86-
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
89+
public static void setCookie(String cookieName,
8790
String cookieValue) {
88-
setCookie(request, response, cookieName, cookieValue, -1);
91+
setCookie(cookieName, cookieValue, -1);
8992
}
9093

9194
/**
9295
* 设置Cookie的值 在指定时间内生效,但不编码
9396
*/
94-
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
95-
String cookieValue, int cookieMaxage) {
96-
setCookie(request, response, cookieName, cookieValue, cookieMaxage, false);
97+
public static void setCookie(String cookieName, String cookieValue, int cookieMaxage) {
98+
setCookie(cookieName, cookieValue, cookieMaxage, false);
9799
}
98100

99101
/**
100102
* 设置Cookie的值 不设置生效时间,但编码
101103
*/
102-
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
103-
String cookieValue, boolean isEncode) {
104-
setCookie(request, response, cookieName, cookieValue, -1, isEncode);
104+
public static void setCookie(String cookieName, String cookieValue, boolean isEncode) {
105+
setCookie(cookieName, cookieValue, -1, isEncode);
105106
}
106107

107108
/**
108109
* 设置Cookie的值 在指定时间内生效, 编码参数
109110
*/
110-
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
111-
String cookieValue, int cookieMaxage, boolean isEncode) {
112-
doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, isEncode);
113-
}
114-
115-
/**
116-
* 设置Cookie的值 在指定时间内生效, 编码参数(指定编码)
117-
*/
118-
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
119-
String cookieValue, int cookieMaxage, String encodeString) {
120-
doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, encodeString);
111+
public static void setCookie(String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {
112+
doSetCookie(cookieName, cookieValue, cookieMaxage, isEncode);
121113
}
122114

123115
/**
124116
* 删除Cookie带cookie域名
125117
*/
126-
public static void deleteCookie(HttpServletRequest request, HttpServletResponse response,
127-
String cookieName) {
128-
doSetCookie(request, response, cookieName, "", -1, false);
118+
public static void deleteCookie(String cookieName) {
119+
doSetCookie(cookieName, "", -1, false);
129120
}
130121

131122
/**
132123
* 设置Cookie的值,并使其在指定时间内生效
133124
*
134125
* @param cookieMaxage cookie生效的最大秒数
135126
*/
136-
private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,
137-
String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {
127+
private static final void doSetCookie(String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {
128+
ServletRequestAttributes attribute = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
129+
HttpServletRequest request = attribute.getRequest();
130+
HttpServletResponse response = attribute.getResponse();
138131
try {
139132
if (cookieValue == null) {
140133
cookieValue = "";
141134
} else if (isEncode) {
142135
cookieValue = URLEncoder.encode(cookieValue, "utf-8");
143136
}
144137
Cookie cookie = new Cookie(cookieName, cookieValue);
145-
if (cookieMaxage > 0)
138+
if (cookieMaxage > 0) {
146139
cookie.setMaxAge(cookieMaxage);
140+
}
147141
if (null != request) {// 设置域名的cookie
148142
String domainName = getDomainName(request);
149143
System.out.println(domainName);
@@ -172,19 +166,16 @@ private static final void doSetCookie(HttpServletRequest request, HttpServletRes
172166
cookieValue = URLEncoder.encode(cookieValue, encodeString);
173167
}
174168
Cookie cookie = new Cookie(cookieName, cookieValue);
175-
if (cookieMaxage > 0)
169+
if (cookieMaxage > 0) {
176170
cookie.setMaxAge(cookieMaxage);
171+
}
177172
if (null != request) {// 设置域名的cookie
178173
String domainName = getDomainName(request);
179174
System.out.println(domainName);
180175
if (!"localhost".equals(domainName)) {
181176
cookie.setDomain(domainName);
182177
}
183178
}
184-
String str = request.getContextPath();
185-
String str1 = request.getLocalAddr();
186-
System.out.println("str:" + str);
187-
System.out.println("str1:" + str1);
188179
cookie.setPath("/");
189180
response.addCookie(cookie);
190181
} catch (Exception e) {

mogu_utils/src/main/java/com/moxi/mogublog/utils/DateUtils.java

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -377,7 +377,7 @@ public static int getCurrentMonthDay() {
377377
/**
378378
* 得到二个日期间的间隔天数
379379
*/
380-
public static int getTwoDay(String sj1, String sj2) {
380+
public static int getDayByTwoDay(String sj1, String sj2) {
381381
SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
382382
Long day = 0L;
383383
try {
@@ -390,6 +390,22 @@ public static int getTwoDay(String sj1, String sj2) {
390390
return day.intValue();
391391
}
392392

393+
/**
394+
* 得到两个日期相差的分钟
395+
* @param lastDate
396+
* @param date
397+
* @return
398+
*/
399+
public static int getMinuteByTwoDay(Date lastDate, Date date) {
400+
Long minute = 0L;
401+
try {
402+
minute = (lastDate.getTime() - date.getTime()) / (60 * 1000);
403+
} catch (Exception e) {
404+
return 0;
405+
}
406+
return minute.intValue();
407+
}
408+
393409
/**
394410
* 判断某个日期属于本周的第几天 (星期一代表第一天)
395411
*

vue_mogu_admin/src/utils/request.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { getToken } from '@/utils/auth'
66
// 创建axios实例
77
const service = axios.create({
88
baseURL: '', // api 的 base_url
9+
withCredentials: true, //允许后台的cookie传递到前端
910
timeout: 100000 // 请求超时时间
1011
})
1112

@@ -33,6 +34,7 @@ service.interceptors.response.use(
3334
// /**
3435
// * code为非20000是抛错 可结合自己业务进行修改
3536
// */
37+
3638
const res = response.data
3739
if (res.code === 'success' || res.code === 'error') {
3840
return response.data

0 commit comments

Comments
 (0)