浏览代码

token 续期问题

lgl 1 年之前
父节点
当前提交
8ed8dd07d7

+ 118 - 0
src/main/java/com/liang/common/config/AuthFilter.java

@@ -0,0 +1,118 @@
1
+package com.liang.common.config;
2
+
3
+import com.liang.common.JsonTool;
4
+import com.liang.common.utils.SecurityUtil;
5
+import com.liang.common.utils.SystemConst;
6
+import com.liang.entity.SysUserInfo;
7
+import lombok.extern.slf4j.Slf4j;
8
+import org.springframework.beans.factory.annotation.Value;
9
+import org.springframework.http.HttpMethod;
10
+import org.springframework.http.HttpStatus;
11
+import org.springframework.stereotype.Component;
12
+import org.springframework.util.AntPathMatcher;
13
+import org.springframework.util.PathMatcher;
14
+import org.springframework.web.filter.OncePerRequestFilter;
15
+
16
+import javax.servlet.FilterChain;
17
+import javax.servlet.ServletException;
18
+import javax.servlet.ServletRequest;
19
+import javax.servlet.ServletResponse;
20
+import javax.servlet.http.HttpServletRequest;
21
+import javax.servlet.http.HttpServletResponse;
22
+import java.io.IOException;
23
+import java.util.ArrayList;
24
+import java.util.List;
25
+import java.util.Optional;
26
+
27
+import static com.liang.common.utils.SecurityUtil.getSysUserInfo;
28
+
29
+/**
30
+ * Restful方式登录<br>
31
+ * 在参数中或者header里加参数login-token作为登录凭证<br>
32
+ * 参数值是登录成功后的返回值中获取
33
+ */
34
+
35
+@Slf4j
36
+@Component
37
+public class AuthFilter extends OncePerRequestFilter {
38
+
39
+    //     排除拦截地址
40
+    private static List<String> excludedPaths = new ArrayList<>();
41
+    static {
42
+        excludedPaths.add("/home/**");
43
+        excludedPaths.add("/login/**");
44
+        excludedPaths.add("/images/**");
45
+        excludedPaths.add("/api/**");
46
+        excludedPaths.add("/css/**");
47
+        excludedPaths.add("/excel/**");
48
+        excludedPaths.add("/js/**");
49
+        excludedPaths.add("/lib/**");
50
+    }
51
+    @Value("${KYGK.session-timeout}")
52
+    private int sessionTimeout;
53
+    private static String info = JsonTool.toJsonString(new ResponseInfo(HttpStatus.UNAUTHORIZED.value(), "token不存在或者过期"));
54
+    @Override
55
+    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
56
+        String uri = request.getServletPath();
57
+        PathMatcher matcher = new AntPathMatcher();
58
+        Optional<String> excludedOptional = excludedPaths.stream().filter(excludePath -> matcher.match(excludePath, uri)).findAny();
59
+        return excludedOptional.isPresent();
60
+    }
61
+    @Override
62
+    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
63
+        if (isAccessAllowed(request, response)) {
64
+            filterChain.doFilter(request, response);
65
+        } else {
66
+            writeResponse(response, request);
67
+        }
68
+    }
69
+
70
+    private boolean isAccessAllowed(ServletRequest request, ServletResponse response) {
71
+        if (HttpMethod.OPTIONS.name().equalsIgnoreCase(((HttpServletRequest) request).getMethod())) {
72
+            return Boolean.TRUE;
73
+        }
74
+
75
+
76
+        try {
77
+
78
+            SysUserInfo user = getSysUserInfo();
79
+            if (null != user) {
80
+                long timeout = SecurityUtil.getRedisUtil().getExpire(SystemConst.SYSTEM_USER_KEY + ":" + SecurityUtil.getUserKey());
81
+                if (timeout > 0) {
82
+                    SecurityUtil.getRedisUtil().set(SystemConst.SYSTEM_USER_KEY + ":" + SecurityUtil.getUserKey(), user, sessionTimeout);
83
+                }
84
+                return true;
85
+            }
86
+        } catch (Exception e) {
87
+            return false;
88
+        }
89
+        return false;
90
+    }
91
+
92
+    private static void writeResponse(HttpServletResponse response, HttpServletRequest request) {
93
+        writeResponse(response, request, info);
94
+    }
95
+
96
+    public static void writeResponse(HttpServletResponse response, HttpServletRequest request,  String info) {
97
+        try {
98
+//            response.setStatus(status);
99
+//            response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
100
+//            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
101
+//            response.setHeader("Access-Control-Allow-Credentials", "true");
102
+////            response.setContentType("application/json;charset=UTF-8");
103
+//            response.sendRedirect("/home/index");
104
+//            response.getWriter().write(info);
105
+
106
+            if("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))){
107
+                //如果是ajax请求
108
+                response.setContentType("application/json;charset=UTF-8");
109
+                response.getWriter().write(info);
110
+                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
111
+            }else{
112
+                response.sendRedirect("/home/index?loginStatus=redirect");
113
+            }
114
+
115
+        } catch (IOException e) {
116
+        }
117
+    }
118
+}

+ 17 - 0
src/main/java/com/liang/common/config/ResponseInfo.java

@@ -0,0 +1,17 @@
1
+package com.liang.common.config;
2
+
3
+import lombok.*;
4
+import lombok.experimental.Accessors;
5
+
6
+import java.io.Serializable;
7
+@Data
8
+@AllArgsConstructor
9
+@NoArgsConstructor
10
+@Accessors(chain = true)
11
+public class ResponseInfo implements Serializable {
12
+
13
+	private static final long serialVersionUID = -4417715614021482064L;
14
+
15
+	private int code;
16
+	private String message;
17
+}

+ 1 - 1
src/main/java/com/liang/common/utils/SecurityUtil.java

@@ -23,7 +23,7 @@ public class SecurityUtil {
23 23
 
24 24
     private static RedisUtil redisUtil;
25 25
 
26
-    private static RedisUtil getRedisUtil() {
26
+    public static RedisUtil getRedisUtil() {
27 27
         if (redisUtil == null) {
28 28
             redisUtil = SpringUtil.getBean("redisUtil");
29 29
         }

+ 36 - 28
src/main/java/com/liang/controller/HomeController.java

@@ -66,34 +66,35 @@ public class HomeController extends BaseController {
66 66
     @RequestMapping(value = "/", method = RequestMethod.GET)
67 67
     public String home(Model model) {
68 68
         String account = getSysUserAccount();
69
-        if(account != null) {
69
+        if (account != null) {
70 70
             model.addAttribute("account", account);
71 71
             return "home/index";
72
-        }
73
-        else{
72
+        } else {
74 73
             return "login/login";
75 74
         }
76
-    }	
77
-	
78
-	@RequestMapping(value = "/login")
79
-    public String login()
80
-    {
81
-      return "login/login";
75
+    }
76
+
77
+    @RequestMapping(value = "/login")
78
+    public String login() {
79
+        return "login/login";
82 80
     }
83 81
 
84 82
 
85 83
     @RequestMapping(value = "/index", method = RequestMethod.GET)
86
-    public ModelAndView user(HttpServletRequest request,HttpSession session) {
84
+    public ModelAndView user(HttpServletRequest request, HttpSession session) {
87 85
         String account = getSysUserAccount();
88
-		if(account != null)
89
-        {
86
+        if (account != null) {
90 87
             ModelAndView mv = new ModelAndView();
91 88
             mv.addObject("account", account);
92 89
             mv.setViewName("home/index");
93 90
             return mv;
94
-        }
95
-        else{
91
+        } else {
92
+            String loginStatus = request.getParameter("loginStatus");
93
+
96 94
             ModelAndView mv = new ModelAndView();
95
+            if (StringUtils.isNotBlank(loginStatus)) {
96
+                mv.addObject("loginStatus", loginStatus);
97
+            }
97 98
             mv.setViewName("login/login");
98 99
             return mv;
99 100
         }
@@ -103,17 +104,17 @@ public class HomeController extends BaseController {
103 104
     @RequestMapping(value = "/doLogin", method = RequestMethod.POST)
104 105
     @ResponseBody
105 106
     public BaseResult doLogin(HttpSession session,
106
-                                @RequestParam(required = true, defaultValue = "", value = "username") String account,
107
-                                @RequestParam(required = true, defaultValue = "", value = "password") String password,
107
+                              @RequestParam(required = true, defaultValue = "", value = "username") String account,
108
+                              @RequestParam(required = true, defaultValue = "", value = "password") String password,
108 109
                               HttpServletRequest request,
109
-                              HttpServletResponse response){
110
+                              HttpServletResponse response) {
110 111
 
111
-        logger.info("account:"+account+" password:"+password);
112
+        logger.info("account:" + account + " password:" + password);
112 113
         SysUserInfo userInfo = sysUserInfoService.getUserByAccount(account);
113 114
 
114 115
         password = SHA256Utils.SHA256Encode(password);
115 116
 
116
-        if(userInfo!= null && userInfo.getPassword().equals(password)){
117
+        if (userInfo != null && userInfo.getPassword().equals(password)) {
117 118
             logger.info("LoginController - doLogin - {}登陆成功!", account);
118 119
             Map<String, Object> resultMap = new HashMap<>();
119 120
             String redisKey = IdGenerate.uuid();
@@ -134,10 +135,11 @@ public class HomeController extends BaseController {
134 135
 //            session.setAttribute("user", userInfo);
135 136
 
136 137
             return BaseResult.success("登录成功!");
137
-        }else{
138
+        } else {
138 139
             return BaseResult.success("登录失败!");
139 140
         }
140 141
     }
142
+
141 143
     /**
142 144
      * 查询页面初始化
143 145
      *
@@ -166,6 +168,7 @@ public class HomeController extends BaseController {
166 168
 
167 169
     /**
168 170
      * 基本资料
171
+     *
169 172
      * @param model
170 173
      * @return
171 174
      */
@@ -179,6 +182,7 @@ public class HomeController extends BaseController {
179 182
 
180 183
     /**
181 184
      * 获取菜单
185
+     *
182 186
      * @return
183 187
      */
184 188
     @RequestMapping(value = "/menuInit", method = RequestMethod.GET)
@@ -197,8 +201,8 @@ public class HomeController extends BaseController {
197 201
         int userId = getSysUserId();
198 202
 
199 203
         Map<String, Object> map = new HashMap<>(16);
200
-        Map<String,Object> home = new HashMap<>(16);
201
-        Map<String,Object> logo = new HashMap<>(16);
204
+        Map<String, Object> home = new HashMap<>(16);
205
+        Map<String, Object> logo = new HashMap<>(16);
202 206
 
203 207
         List<Map> menuList = sysPermissionInfoService.menuInit(userId);
204 208
 
@@ -222,7 +226,7 @@ public class HomeController extends BaseController {
222 226
 
223 227
         for (Map temp : menuList) {
224 228
             MenuVo menuVO = new MenuVo();
225
-            menuVO.setPermissionId((String)temp.get("permission_id"));
229
+            menuVO.setPermissionId((String) temp.get("permission_id"));
226 230
             menuVO.setParentId((String) temp.get("parent_id"));
227 231
             menuVO.setHref((String) temp.get("href"));
228 232
             menuVO.setTitle((String) temp.get("title"));
@@ -251,8 +255,9 @@ public class HomeController extends BaseController {
251 255
 
252 256
     /**
253 257
      * 获取菜单的树状结构(双重遍历法list转tree)
258
+     *
254 259
      * @param menuList 菜单列表
255
-     * @param topPid 顶级ID
260
+     * @param topPid   顶级ID
256 261
      * @return
257 262
      */
258 263
     private List<MenuVo> toTree(List<MenuVo> menuList, String topPid) {
@@ -282,11 +287,12 @@ public class HomeController extends BaseController {
282 287
 
283 288
     /**
284 289
      * 修改密码操作
290
+     *
285 291
      * @param old_password
286 292
      * @param new_password
287 293
      * @return
288 294
      */
289
-    @RequestMapping(value="/doUpdatePassword",method = RequestMethod.POST)
295
+    @RequestMapping(value = "/doUpdatePassword", method = RequestMethod.POST)
290 296
     @ResponseBody
291 297
     public BaseResult doUpdatePassword(@RequestParam("old_password") String old_password,
292 298
                                        @RequestParam("new_password") String new_password) {
@@ -307,7 +313,7 @@ public class HomeController extends BaseController {
307 313
             userInfo.setPassword(new_password);
308 314
 
309 315
             int num = sysUserInfoService.resetPass(userInfo);
310
-            if(num > 0)
316
+            if (num > 0)
311 317
                 return BaseResult.success("密码修改成功");
312 318
             else
313 319
                 return BaseResult.failure("修改密码失败");
@@ -318,9 +324,10 @@ public class HomeController extends BaseController {
318 324
 
319 325
     /**
320 326
      * 退出登录
327
+     *
321 328
      * @return
322 329
      */
323
-    @RequestMapping(value = "/outLogin",method = RequestMethod.GET)
330
+    @RequestMapping(value = "/outLogin", method = RequestMethod.GET)
324 331
     public String outLogin() {
325 332
         String userKey = SecurityUtil.getUserKey();
326 333
         // 先从redis里面拿出菜单信息,拿不到的话,再去手动查询
@@ -335,13 +342,14 @@ public class HomeController extends BaseController {
335 342
 
336 343
     /**
337 344
      * 修改用户信息
345
+     *
338 346
      * @return
339 347
      */
340 348
     @RequestMapping(value = "/doUpdate", method = RequestMethod.POST)
341 349
     @ResponseBody
342 350
     public BaseResult doUpdate(@RequestParam(value = "userId") Integer userId,
343 351
                                @RequestParam(value = "phone") String phone,
344
-                               @RequestParam(required = false, defaultValue = "", value = "email") String email){
352
+                               @RequestParam(required = false, defaultValue = "", value = "email") String email) {
345 353
 
346 354
         SysUserInfo userInfo = new SysUserInfo();
347 355
         userInfo.setUserId(userId);

+ 20 - 13
src/main/resources/static/js/lay-config.js

@@ -109,16 +109,23 @@ $(document).on("click", "td div.laytable-cell-checkbox div.layui-form-checkbox",
109 109
  * 设置AJAX的全局默认选项,
110 110
  * 当AJAX请求会话过期时,跳转到登陆页面
111 111
  */
112
-// $.ajaxSetup({
113
-//     complete: function(XMLHttpRequest, textStatus){
114
-//         if (XMLHttpRequest.responseJSON.code === 401) {
115
-//             layer.alert('会话已过期,请重新登录', function(index){
116
-//                 layer.close(index);
117
-//                 window.location.href = AjaxUtil.ctx + "home/login";
118
-//             });
119
-//         }
120
-//     }
121
-// } );
112
+$.ajaxSetup({
113
+    complete: function (XMLHttpRequest, textStatus) {
114
+        console.log(XMLHttpRequest)
115
+        console.log("前端重定向")
116
+        if (XMLHttpRequest.responseJSON.code === 401) {
117
+            layer.alert('会话已过期,请重新登录', function (index) {
118
+                layer.close(index);
119
+                var win = window;
120
+                while (win != win.top) {
121
+                    win = win.top;
122
+                }
123
+                //重新跳转到 login.html
124
+                win.location.href = "/home/index";
125
+            });
126
+        }
127
+    }
128
+});
122 129
 
123 130
 /**
124 131
  * 配置layer.open的宽度和高度
@@ -385,14 +392,14 @@ function toDateString(time, format) {
385 392
  * @param length
386 393
  * @returns {string}
387 394
  */
388
-function digit(num, length){
395
+function digit(num, length) {
389 396
     var str = '';
390 397
     num = String(num);
391 398
     length = length || 2;
392
-    for(var i = num.length; i < length; i++){
399
+    for (var i = num.length; i < length; i++) {
393 400
         str += '0';
394 401
     }
395
-    return num < Math.pow(10, length) ? str + (num|0) : num;
402
+    return num < Math.pow(10, length) ? str + (num | 0) : num;
396 403
 }
397 404
 
398 405
 /**

+ 13 - 11
src/main/resources/templates/login/login.html

@@ -315,11 +315,11 @@
315 315
                     <span class="bind-password icon icon-4"></span>
316 316
                 </div>
317 317
 
318
-<!--                <div id="validatePanel" class="item" style="width: 167px;">-->
319
-<!--                    <span class="icon icon-1"></span>-->
320
-<!--                    <input type="text" id="captcha" name="captcha" placeholder="请输入验证码" autocomplete="off" maxlength="4">-->
321
-<!--                    <img id="ver_btn" class="validateImg" alt="看不清? 点击刷新" title="看不清? 点击刷新"/>-->
322
-<!--                </div>-->
318
+                <!--                <div id="validatePanel" class="item" style="width: 167px;">-->
319
+                <!--                    <span class="icon icon-1"></span>-->
320
+                <!--                    <input type="text" id="captcha" name="captcha" placeholder="请输入验证码" autocomplete="off" maxlength="4">-->
321
+                <!--                    <img id="ver_btn" class="validateImg" alt="看不清? 点击刷新" title="看不清? 点击刷新"/>-->
322
+                <!--                </div>-->
323 323
 
324 324
             </div>
325 325
             <div class="tip">
@@ -350,11 +350,15 @@
350 350
     AjaxUtil.ctx = /*[[@{/}]]*/'';
351 351
     // 在页面加载完毕后调用拦截器函数
352 352
 
353
-    layui.use(['form', 'layNotify'], function () {
353
+    layui.use(['form', 'layNotify', 'layer'], function () {
354 354
 
355 355
         var form = layui.form,
356 356
             layNotify = layui.layNotify;
357
-
357
+        var layer = layui.layer;
358
+        var loginStatus = [[${loginStatus}]];
359
+        if (loginStatus === 'redirect') {
360
+            layer.alert("会话已过期,请重新登录")
361
+        }
358 362
         // 登录过期的时候,跳出ifram框架
359 363
         if (top.location != self.location) {
360 364
             top.location = self.location;
@@ -488,9 +492,10 @@
488 492
             }
489 493
         });
490 494
 
491
-        function redirection(){
495
+        function redirection() {
492 496
             window.location.replace("http://10.208.114.107:8081/home/")
493 497
         }
498
+
494 499
         // 登陆中
495 500
         function logining() {
496 501
             document.getElementById("btn_login").setAttribute("disabled", true);//设置不可点击
@@ -525,12 +530,9 @@
525 530
         // }
526 531
 
527 532
 
528
-
529 533
     });
530 534
 
531 535
 
532
-
533
-
534 536
 </script>
535 537
 
536 538
 </body>