Sfoglia il codice sorgente

修改jwt过滤器加载顺序,对token解密后二次封装到request

xusl 2 anni fa
parent
commit
633bfe478a

+ 6 - 3
backend/src/main/java/com/jiayue/ssi/config/WebSecurityConfig.java

@@ -41,6 +41,8 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
     CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;
     @Autowired
     RestAccessDeniedHandler restAccessDeniedHandler;
+    @Autowired
+    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
 
 
     @Bean
@@ -60,7 +62,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
         httpSecurity.addFilterBefore(new VerifySmFilter(), UsernamePasswordAuthenticationFilter.class);
         httpSecurity.addFilterBefore(new VerifyCodeFilter(), UsernamePasswordAuthenticationFilter.class);
         httpSecurity.addFilterBefore(new MailCodeFilter(), UsernamePasswordAuthenticationFilter.class);
-        httpSecurity.addFilterBefore(new JwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
+        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
         httpSecurity
                 // 由于使用的是JWT,我们这里不需要csrf
                 .csrf().disable()
@@ -69,14 +71,15 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
                 .and().authorizeRequests()
 //                .antMatchers("/user/login","/captchaImage").permitAll()
                 .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
-                .antMatchers("/getVerifyCode","/getMailCode").permitAll()
+//                .antMatchers("/getVerifyCode/**","/getMailCode/**").permitAll()
                 // 除上面外的所有请求全部需要鉴权认证
                 .anyRequest().authenticated()
                 .and().headers().cacheControl();
         httpSecurity.formLogin().loginProcessingUrl("/user/login")
                 .successHandler(customAuthenticationSuccessHandler)
                 .failureHandler(customAuthenticationFailureHandler);
-        httpSecurity.exceptionHandling().authenticationEntryPoint(entryPointUnauthorizedHandler).accessDeniedHandler(restAccessDeniedHandler);;
+        httpSecurity.exceptionHandling().authenticationEntryPoint(entryPointUnauthorizedHandler).accessDeniedHandler(restAccessDeniedHandler);
+
 
     }
 

+ 2 - 1
backend/src/main/java/com/jiayue/ssi/filter/JwtAuthenticationTokenFilter.java

@@ -14,6 +14,7 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticatio
 import org.springframework.security.core.context.SecurityContextHolder;
 import org.springframework.security.core.userdetails.UserDetails;
 import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
+import org.springframework.stereotype.Component;
 import org.springframework.util.StringUtils;
 import org.springframework.web.filter.OncePerRequestFilter;
 import com.jiayue.ssi.util.JwtTokenUtil;
@@ -25,7 +26,7 @@ import lombok.RequiredArgsConstructor;
  * @author: yh
  * @create: 2020-03-19 13:05
  **/
-@RequiredArgsConstructor
+@Component
 @Order(10)
 public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
 

+ 35 - 35
backend/src/main/java/com/jiayue/ssi/filter/VerifySmFilter.java

@@ -28,28 +28,31 @@ public class VerifySmFilter extends OncePerRequestFilter {
 
     @Override
     protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
+        Map<String,Object> stringToMap = new HashMap(16);
+        ParameterRequestWrapper initWrapper = new ParameterRequestWrapper(request);
         // 不是登录操作
-//        if (!("POST".equalsIgnoreCase(request.getMethod()) && defaultFilterProcessUrl.equals(request.getServletPath()))) {
-//            // 验证token
-//            String tokenStr = request.getHeader("Authorization");
-//            if (StringUtils.isNotEmpty(tokenStr)){
-//                // 解密token
-//                String decryptTokenStr = SM2CryptUtils.decrypt(tokenStr,SecretKeyConstants.SERVER_PRIVATE_KEY);
-//                System.out.println("接收token后解密:"+decryptTokenStr);
-//                String tokenSign = request.getHeader("TokenSign");
-//                // 验证签名
-//                boolean verifySign = SM2CryptUtils.verifySign(SecretKeyConstants.CLIENT_PUBLIC_KEY,decryptTokenStr,tokenSign);
-//                if (!verifySign){
-//                    // 验签失败
-//                    ResponseInfo.doResponse(response,"token验签失败,不能访问系统!",401);
-//                    return;
-//                }
-//            }
-//            else{
-//                ResponseInfo.doResponse(response,"没有令牌权限,不能访问系统!",401);
-//                return;
-//            }
-//        }
+        if (!("POST".equalsIgnoreCase(request.getMethod()) && defaultFilterProcessUrl.equals(request.getServletPath()))) {
+            // 验证token
+            String tokenStr = request.getHeader("Authorization");
+            if (StringUtils.isNotEmpty(tokenStr)){
+                // 解密token
+                String decryptTokenStr = SM2CryptUtils.decrypt(tokenStr,SecretKeyConstants.SERVER_PRIVATE_KEY);
+                System.out.println("接收token后解密:"+decryptTokenStr);
+                String tokenSign = request.getHeader("TokenSign");
+                // 验证签名
+                boolean verifySign = SM2CryptUtils.verifySign(SecretKeyConstants.CLIENT_PUBLIC_KEY,decryptTokenStr,tokenSign);
+                if (!verifySign){
+                    // 验签失败
+                    ResponseInfo.doResponse(response,"token验签失败,不能访问系统!",401);
+                    return;
+                }
+                initWrapper.addHeader("Authorization",decryptTokenStr);
+            }
+            else{
+                ResponseInfo.doResponse(response,"没有令牌权限,不能访问系统!",401);
+                return;
+            }
+        }
         // 解密后的参数字符串
         String decryptStr = "";
         if ("POST".equalsIgnoreCase(request.getMethod())){
@@ -82,6 +85,13 @@ public class VerifySmFilter extends OncePerRequestFilter {
                     ResponseInfo.doResponse(response,"参数验签失败,不能访问系统!",401);
                     return;
                 }
+                if (!"".equals(decryptStr)){
+                    String[] tempInterval = decryptStr.split("&");
+                    for (int i=0;i<tempInterval.length;i++){
+                        String[] fieldKeyValue = tempInterval[i].split("=");
+                        stringToMap.put(fieldKeyValue[0],fieldKeyValue[1]);
+                    }
+                }
             }
         }
         else{
@@ -121,23 +131,13 @@ public class VerifySmFilter extends OncePerRequestFilter {
                     ResponseInfo.doResponse(response,"参数验签失败,不能访问系统!",401);
                     return;
                 }
-            }
-        }
-
-        Map<String,Object> stringToMap = new HashMap(16);
-        if (!"".equals(decryptStr)){
-            if ("POST".equalsIgnoreCase(request.getMethod())){
-                String[] tempInterval = decryptStr.split("&");
-                for (int i=0;i<tempInterval.length;i++){
-                    String[] fieldKeyValue = tempInterval[i].split("=");
-                    stringToMap.put(fieldKeyValue[0],fieldKeyValue[1]);
+                if (!"".equals(decryptStr)){
+                    stringToMap = JSONUtil.parseObj(decryptStr).getRaw();
                 }
             }
-            else{
-                stringToMap = JSONUtil.parseObj(decryptStr).getRaw();
-            }
         }
-        ParameterRequestWrapper pr = new ParameterRequestWrapper(request, stringToMap);
+
+        ParameterRequestWrapper pr = new ParameterRequestWrapper(initWrapper, stringToMap);
         filterChain.doFilter(pr, response);
     }
 }

+ 12 - 7
backend/src/main/java/com/jiayue/ssi/handler/CustomAuthenticationSuccessHandler.java

@@ -1,13 +1,17 @@
 package com.jiayue.ssi.handler;
 
 import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
 
 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
 import com.jiayue.ssi.constant.CacheConstants;
+import com.jiayue.ssi.constant.SecretKeyConstants;
 import com.jiayue.ssi.util.LocalCache;
+import com.jiayue.ssi.util.SM2CryptUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.security.core.Authentication;
 import org.springframework.security.core.context.SecurityContextHolder;
@@ -36,18 +40,19 @@ public class CustomAuthenticationSuccessHandler extends SavedRequestAwareAuthent
         String username = request.getParameter("username");
         // 删除缓存邮箱口令
         LocalCache.remove(CacheConstants.MAIL_CODE_KEY + username);
-
         SysUser sysUser = (SysUser) authentication.getPrincipal();
         SecurityContextHolder.getContext().setAuthentication(authentication);
         String token = jwtTokenUtil.generateToken(sysUser);
-//        SysUser sysUser = sysUserService.findByUserName(user.getUsername());
-//        sysUser.setPwdErrNum(0);
-//        sysUser.setStatus("0");
-//        sysUserService.save(sysUser);
+        String obj = JSONUtil.toJsonStr(ResponseVO.success(token));
+        // token加密处理
+        String encrypt = SM2CryptUtils.encrypt(obj, SecretKeyConstants.CLIENT_PUBLIC_KEY);
+        // token签名
+        String signStr = SM2CryptUtils.sign(SecretKeyConstants.SERVER_PRIVATE_KEY,obj);
+        String secretResult = "token="+encrypt+"&tokenSign="+signStr;
         response.addHeader("Access-Control-Allow-Origin", "*");
         response.setStatus(200);
-        response.setContentType("application/json;charset=UTF-8");
-        response.getWriter().write(JSONUtil.toJsonStr(ResponseVO.success(token)));
+        response.setContentType("text/html;charset=UTF-8");
+        response.getWriter().write(secretResult);
     }
 
 

+ 41 - 4
backend/src/main/java/com/jiayue/ssi/servlet/ParameterRequestWrapper.java

@@ -1,9 +1,6 @@
 package com.jiayue.ssi.servlet;
 
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Vector;
+import java.util.*;
 
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletRequestWrapper;
@@ -17,6 +14,7 @@ import javax.servlet.http.HttpServletRequestWrapper;
 public class ParameterRequestWrapper extends HttpServletRequestWrapper {
 
     private Map<String, String[]> params = new HashMap<>();
+    private Map<String, String> headerMap = new HashMap<>();
 
     public ParameterRequestWrapper(HttpServletRequest request) {
         super(request);
@@ -69,4 +67,43 @@ public class ParameterRequestWrapper extends HttpServletRequestWrapper {
             }
         }
     }
+
+    /**
+     * add a header with given name and value
+     *
+     * @param name
+     * @param value
+     */
+    public void addHeader(String name, String value) {
+        headerMap.put(name, value);
+    }
+    @Override
+    public String getHeader(String name) {
+        String headerValue = super.getHeader(name);
+        if (headerMap.containsKey(name)) {
+            headerValue = headerMap.get(name);
+        }
+        return headerValue;
+    }
+
+    /**
+     * get the Header names
+     */
+    @Override
+    public Enumeration<String> getHeaderNames() {
+        List<String> names = Collections.list(super.getHeaderNames());
+        for (String name : headerMap.keySet()) {
+            names.add(name);
+        }
+        return Collections.enumeration(names);
+    }
+
+    @Override
+    public Enumeration<String> getHeaders(String name) {
+        List<String> values = Collections.list(super.getHeaders(name));
+        if (headerMap.containsKey(name)) {
+            values = Arrays.asList(headerMap.get(name));
+        }
+        return Collections.enumeration(values);
+    }
 }

+ 5 - 0
backend/src/main/java/com/jiayue/ssi/util/JwtTokenUtil.java

@@ -147,4 +147,9 @@ public class JwtTokenUtil {
         System.out.println("jwt body:" + body);
         System.out.println("jwt body user-id:" + body.get("user_id", String.class));
     }
+
+    public static void main(String[] args) {
+        String token="eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImV4cCI6MjMwODg3NjM3NywiaWF0IjoxNjc4MTU2Mzc3NzU5fQ.imVgkdOog0YVVzhlS-mIFfvz9FyKsdKzjT21YhU2zs1o35scTs3qhyy7kX8ZtXJEJKvdRR5SuWN07DCi-57eew";
+        System.out.println(new JwtTokenUtil().getUsernameFromToken(token));
+    }
 }

+ 0 - 272
backend/src/test/java/com/jiayue/ssi/service/Test1.java

@@ -1,272 +0,0 @@
-package com.jiayue.ssi.service;
-
-import cn.hutool.core.convert.Convert;
-
-import java.io.FileOutputStream;
-import java.io.OutputStreamWriter;
-import java.util.*;
-import java.util.stream.Collectors;
-
-/**
- * TODO
- *
- * @author xsl
- * @version 3.0
- */
-public class Test1 {
-    public static void main(String[] args) throws Exception{
-        Test1 test1 = new Test1();
-        List<String> qjList = new ArrayList<>();
-        qjList.add("3:2:1");
-        qjList.add("1:2:3");
-        qjList.add("2:1:3");
-        qjList.add("3:1:2");
-
-        List<String> joList = new ArrayList<>();
-        joList.add("2:4");
-        joList.add("4:2");
-
-        Integer[] r1 = {
-        1
-//        2,
-//        4,
-//        3,
-//        6,
-//        5,
-//        7,
-//        8,
-//        9,
-//        10,
-//        12,
-//        11,
-//        14,
-//        13,
-//        16,
-//        18,
-//        19
-        };
-
-        Integer[] r2 = {
-        10,
-//        4,
-//        8,
-//        12,
-//        16,
-//        7,
-//        3,
-//        5,
-//        9,
-//        13,
-//        15,
-//        20,
-//        6,
-        14,
-//        2,
-//        11,
-//        18,
-//        17
-//        26
-        };
-
-        Integer[] r3 = {
-//        11,
-//        12,
-//        13,
-//        17,
-//        15,
-//        8,
-//        10,
-//        14,
-//        18,
-//        19,
-//        5,
-//        9,
-//        21,
-//        20,
-//        22,
-//        4,
-//        6,
-//        7,
-        16
-//        23
-        };
-
-        Integer[] r4 = {
-        20,
-//        15,
-//        18,
-//        23,
-//        14,
-//        22,
-//        17,
-//        13,
-//        19,
-//        25,
-//        21,
-//        16,
-//        24,
-//        27,
-//        28,
-//        10,
-//        9,
-//        26,
-//        12,
-//        11,
-//        29,
-//        7,
-//        30,
-//        31
-        };
-
-        Integer[] r5 = {
-
-        25
-//        27,
-//        30,
-//        22,
-//        24,
-//        26,
-//        29,
-//        21,
-//        28,
-//        32,
-//        31
-//        20,
-//        18,
-//        19,
-//        23,
-//        16,
-//        17,
-//        15,
-//        7,
-//        10,
-//        12,
-//        11,
-//        14
-        };
-
-
-        Integer[] r6 = {
-        32
-//        30,
-//        33
-//        31
-//        29,
-//        27,
-//        26,
-//        25,
-//        28,
-//        22,
-//        24,
-//        21,
-//        20,
-//        23,
-//        16,
-//        19,
-//        15,
-//        17
-        };
-
-
-        List<Integer> r1List = Arrays.asList(r1);
-        List<Integer> r2List = Arrays.asList(r2);
-        List<Integer> r3List = Arrays.asList(r3);
-        List<Integer> r4List = Arrays.asList(r4);
-        List<Integer> r5List = Arrays.asList(r5);
-        List<Integer> r6List = Arrays.asList(r6);
-
-        Collections.sort(r1List);
-        Collections.sort(r2List);
-        Collections.sort(r3List);
-        Collections.sort(r4List);
-        Collections.sort(r5List);
-        Collections.sort(r6List);
-
-        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("d:\\test\\codeList.txt"), "UTF-8");
-        for (Integer r1v:r1List){
-            for (Integer r2v:r2List){
-                if (r1v.intValue()>=r2v.intValue()){
-                    continue;
-                }
-                for (Integer r3v:r3List){
-                    if (r2v.intValue()>=r3v.intValue()){
-                        continue;
-                    }
-                    for (Integer r4v:r4List){
-                        if (r3v.intValue()>=r4v.intValue()){
-                            continue;
-                        }
-                        for (Integer r5v:r5List){
-                            if (r4v.intValue()>=r5v.intValue()){
-                                continue;
-                            }
-                            for (Integer r6v:r6List){
-                                if (r5v.intValue()>=r6v.intValue()){
-                                    continue;
-                                }
-                                List<Integer> finalList = new ArrayList();
-                                finalList.add(r1v);
-                                finalList.add(r2v);
-                                finalList.add(r3v);
-                                finalList.add(r4v);
-                                finalList.add(r5v);
-                                finalList.add(r6v);
-                                String joStr = test1.pfScaleCal(finalList);
-                                String qjStr = test1.intervalScaleCal(finalList);
-
-//                                List<String> resultList = qjList.stream().filter(x->x.contains(qjStr)).collect(Collectors.toList());
-//                                if (resultList.size()>0){
-                                    // 有区间,判别奇偶
-                                    List<String> joResult = joList.stream().filter(x->x.contains(joStr)).collect(Collectors.toList());
-                                    if (joResult.size()>0){
-                                        osw.write("找到匹配==>奇偶--区间:"+joStr+"--"+qjStr+" "+Convert.toStr(finalList)+"\r\n");
-                                    }
-//                                }
-                            }
-                        }
-                    }
-                }
-            }
-        }
-        osw.close();
-    }
-
-    public String pfScaleCal(List<Integer> redList){
-        int pVal = 0;
-        int fVal = 0;
-        for (Integer red:redList) {
-            if (red.intValue()%2==0){
-                // 偶数
-                fVal++;
-            }
-            else{
-                pVal++;
-            }
-        }
-        return pVal+":"+fVal;
-    }
-
-    /**
-     * 区间比
-     * @param redList
-     * @return
-     */
-    public String intervalScaleCal(List<Integer> redList){
-        int q1 = 0;
-        int q2 = 0;
-        int q3 = 0;
-        for (Integer red:redList) {
-            int redInt = red.intValue();
-            if (redInt>=1 && redInt<=11){
-                q1++;
-            }
-            else if (redInt>=12 && redInt<=22){
-                q2++;
-            }
-            else if (redInt>=23 && redInt<=33){
-                q3++;
-            }
-        }
-        return q1+":"+q2+":"+q3;
-    }
-}

+ 149 - 175
ui/src/main.js

@@ -46,9 +46,9 @@ Vue.use(ElementUI, {locale})
 Vue.prototype.$fpath = require('path')
 Vue.config.productionTip = false
 Vue.prototype.$axios = axios.create({
-    baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
-    // withCredentials: true, // send cookies when cross-domain requests
-    timeout: 1000 * 60 * 10 // request timeout
+  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
+  // withCredentials: true, // send cookies when cross-domain requests
+  timeout: 1000 * 60 * 10 // request timeout
 })
 VXETable.setup({
   validArgs: 'obsolete' // 将自定义校验参数还原为 Function(rule, cellValue, callback)
@@ -60,210 +60,184 @@ let publicKey2 = '041967638ca43d4577d8dba166bff4437fde944270101f398a95b846ec2f81
 let privateKey1 = '27ce6eec39dbf3b564a77c4da1e129fe1ba01a92f6d61055a33ed14ffcbc949e'
 
 Vue.prototype.$axios.interceptors.request.use(
-    config => {
-      // get请求映射params参数
-      if (config.method === 'get' && config.params) {
-        // 参数加密
-        let encryptParam = doEncrypt(JSON.stringify(config.params))
-        // 参数签名
-        let paramSign = doSign(JSON.stringify(config.params))
-        let result = 'secretData='+encryptParam+'&paramSign='+paramSign
-        config.params = result
-      }
+  config => {
+    // get请求映射params参数
+    if (config.method === 'get' && config.params) {
+      // 参数加密
+      let encryptParam = doEncrypt(JSON.stringify(config.params))
+      // 参数签名
+      let paramSign = doSign(JSON.stringify(config.params))
+      let result = 'secretData=' + encryptParam + '&paramSign=' + paramSign
+      config.params = result
+    }
 
-      if (config.method === 'post' || config.method === 'put') {
-        if (config.url!='/getMailCode'){
-          if (config.data!==undefined){
-            // 参数加密
-            let encryptParam = doEncrypt(config.data.toString())
-            // 参数签名
-            let paramSign = doSign(config.data.toString())
-            let result = 'secretData='+encryptParam+'&paramSign='+paramSign
-            config.data = result
-          }
+    if (config.method === 'post' || config.method === 'put') {
+      if (config.url != '/getMailCode') {
+        if (config.data !== undefined) {
+          // 参数加密
+          let encryptParam = doEncrypt(config.data.toString())
+          // 参数签名
+          let paramSign = doSign(config.data.toString())
+          let result = 'secretData=' + encryptParam + '&paramSign=' + paramSign
+          config.data = result
         }
       }
+    }
 
-      if (getBrowserToken()) { // 判断是否存在token,如果存在的话,则每个http header都加上token
-        let tokenStr = doEncrypt(getBrowserToken())
-        config.headers['Authorization']= tokenStr
-        config.headers['TokenSign']= doSign(getBrowserToken())
-      }
-      return config
-    },
-    error => {
-        // do something with request error
-        console.log(error) // for debug
-        return Promise.reject(error)
+    if (sessionStorage.getItem("token")!=="undefined" && sessionStorage.getItem("token")!==undefined && sessionStorage.getItem("token")!=null) { // 判断是否存在token,如果存在的话,则每个http header都加上token
+      alert('存在')
+      let tokenStr = doEncrypt(sessionStorage.getItem("token"))
+      config.headers['Authorization'] = tokenStr
+      config.headers['TokenSign'] = doSign(sessionStorage.getItem("token"))
     }
+    return config
+  },
+  error => {
+    // do something with request error
+    console.log(error) // for debug
+    return Promise.reject(error)
+  }
 )
 
 function getBrowserUser() {
-    var user = "";
-    var ca = document.cookie.split(';');
-    for (var i = 0; i < ca.length; i++) {
-        var c = ca[i].trim();
-        if (c.indexOf("user=") == 0){
-            user = c.substring("user=".length, c.length);
-        }
+  var user = "";
+  var ca = document.cookie.split(';');
+  for (var i = 0; i < ca.length; i++) {
+    var c = ca[i].trim();
+    if (c.indexOf("user=") == 0) {
+      user = c.substring("user=".length, c.length);
     }
-    return user
+  }
+  return user
 }
 
 // response interceptor
 Vue.prototype.$axios.interceptors.response.use(
-    /**
-     * If you want to get http information such as headers or status
-     * Please return  response => response
-     */
-
-    /**
-     * Determine the request status by custom code
-     * Here is just an example
-     * You can also judge the status by HTTP Status Code
-     */
-    response => {
-        // 处理下载文件
-        if (response.headers && response.headers['content-type'] && (response.headers['content-type'].indexOf('application/x-msdownload') != -1)) {
-            // 创建一个blob对象,file的一种
-            const blob = new Blob([response.data], {type: response.headers['content-type']})
-            const fileName = decodeURI(response.headers['content-disposition'].split('=')[1])
-            if (window.navigator.msSaveOrOpenBlob) {
-                // 兼容IE10
-                navigator.msSaveBlob(blob, fileName)
-            } else {
-                // 非IE下载
-                const elink = document.createElement('a')
-                elink.download = fileName
-                elink.style.display = 'none'
-                elink.href = URL.createObjectURL(blob)
-                document.body.appendChild(elink)
-                elink.click()
-                URL.revokeObjectURL(elink.href) // 释放URL 对象
-                document.body.removeChild(elink)
-            }
-            response.data = ''
-            response.headers['content-type'] = 'text/json'
-            return response
-        } else {
-            const res = response.data
-            let returnStr = res.split("&")
-            let returnData = returnStr[0].split("=")[1]
-            let returnSign = returnStr[1].split("=")[1]
-            // 解密
-            let decData = doDecryptStr(returnData)
-            // 验签
-            let verifyResult = doVerifySignature(decData,returnSign)
-
-          if (!verifyResult){
-            return Promise.reject(new Error('返回数据验签失败' || 'Error'))
-          }
-
-          let data = JSON.parse(decData)
-          alert(data)
-            // if the custom code is not 20000, it is judged as an error.
-            //console.log(res.code)
-            if (data.code !== 0) {
-                Message({
-                    message: data.message || 'Error',
-                    type: 'error',
-                    duration: 5 * 1000
-                })
+  /**
+   * If you want to get http information such as headers or status
+   * Please return  response => response
+   */
 
-                // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
-                if (data.code === 50008 || data.code === 50012 || data.code === 50014) {
-                    // to re-login
-                    MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
-                        confirmButtonText: 'Re-Login',
-                        cancelButtonText: 'Cancel',
-                        type: 'warning'
-                    }).then(() => {
-                        store.dispatch('user/resetToken').then(() => {
-                            location.reload()
-                        })
-                    })
-                }
-                return Promise.reject(new Error(data.message || 'Error'))
-            } else {
-                return data
-            }
-        }
-    },
-    error => {
-        if (error.response) {
-            switch (error.response.status) {
-                case 401:
-                    console.log('用户验证失败!')
-                    // 返回 401 清除token信息并跳转到登录页面
-                    removeToken()
-                    resetRouter()
-                    Message({
-                        message: error.response.data,
-                        type: 'error',
-                        duration: 5 * 1000
-                    })
-                    break
-                case 403:
-                    console.log('登录超时!')
-                    // 返回 401 清除token信息并跳转到登录页面
-                    removeToken()
-                    resetRouter()
-                    router.push('/login')
-                    Message({
-                        message: '登录超时',
-                        type: 'error',
-                        duration: 5 * 1000
-                    })
-                    break
-                case 500:
-                    Message({
-                        message: '服务器关闭了!请联系相关工作人员',
-                        type: 'error',
-                        duration: 5 * 1000
-                    })
-                    removeToken()
-                    resetRouter()
-                    router.push('/login')
-                    break
-                case 504:
-                    console.log('服务器关闭了!')
-                    resetRouter()
-                    break
-            }
-        }
-        /*    console.log('err' + error) // for debug
+  /**
+   * Determine the request status by custom code
+   * Here is just an example
+   * You can also judge the status by HTTP Status Code
+   */
+  response => {
+      const res = response.data
+      let returnStr = res.split("&")
+      let returnData = returnStr[0].split("=")[1]
+      let returnSign = returnStr[1].split("=")[1]
+      // 解密
+      let decData = doDecryptStr(returnData)
+      // 验签
+      let verifyResult = doVerifySignature(decData, returnSign)
+      if (!verifyResult) {
+        return Promise.reject(new Error('返回数据验签失败' || 'Error'))
+      }
+      let data = JSON.parse(decData)
+      // if the custom code is not 20000, it is judged as an error.
+      //console.log(res.code)
+      if (data.code !== 0) {
         Message({
-          message: error.message,
+          message: data.message || 'Error',
           type: 'error',
           duration: 5 * 1000
-        })*/
-        return Promise.reject(error)
+        })
+
+        // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
+        if (data.code === 50008 || data.code === 50012 || data.code === 50014) {
+          // to re-login
+          MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
+            confirmButtonText: 'Re-Login',
+            cancelButtonText: 'Cancel',
+            type: 'warning'
+          }).then(() => {
+            store.dispatch('user/resetToken').then(() => {
+              location.reload()
+            })
+          })
+        }
+        return Promise.reject(new Error(data.message || 'Error'))
+      } else {
+        return data
+      }
+  },
+  error => {
+    if (error.response) {
+      switch (error.response.status) {
+        case 401:
+          console.log('用户验证失败!')
+          // 返回 401 清除token信息并跳转到登录页面
+          removeToken()
+          resetRouter()
+          Message({
+            message: error.response.data,
+            type: 'error',
+            duration: 5 * 1000
+          })
+          break
+        case 403:
+          console.log('登录超时!')
+          // 返回 401 清除token信息并跳转到登录页面
+          removeToken()
+          resetRouter()
+          router.push('/login')
+          Message({
+            message: '登录超时',
+            type: 'error',
+            duration: 5 * 1000
+          })
+          break
+        case 500:
+          Message({
+            message: '服务器关闭了!请联系相关工作人员',
+            type: 'error',
+            duration: 5 * 1000
+          })
+          removeToken()
+          resetRouter()
+          router.push('/login')
+          break
+        case 504:
+          console.log('服务器关闭了!')
+          resetRouter()
+          break
+      }
     }
+    /*    console.log('err' + error) // for debug
+    Message({
+      message: error.message,
+      type: 'error',
+      duration: 5 * 1000
+    })*/
+    return Promise.reject(error)
+  }
 )
 
 new Vue({
-    el: '#app',
-    router,
-    store,
-    render: h => h(App)
+  el: '#app',
+  router,
+  store,
+  render: h => h(App)
 })
 
-export function test(){
+export function test() {
   let sm2 = require('sm-crypto').sm2;
   let cipherMode = 1
   // 加密
   let encryptData = sm2.doEncrypt('1122加密', '0460ff8c8c306fe62f6f9d11c5c82c30d10bbbc703da094e423072cac7dc663c97fad52eccb34f311f47a07f280de157ba4f2aa659cabe749121384b9376ea2ed2', cipherMode);
   let sm3 = require('sm-crypto').sm2;
   // 签名
-  let sign = sm3.doSignature('1122加密','6155d63ee27cbeca07f3e40c4f8856f1be8119fcbda1aadc7e0e595e52bad7bd')
+  let sign = sm3.doSignature('1122加密', '6155d63ee27cbeca07f3e40c4f8856f1be8119fcbda1aadc7e0e595e52bad7bd')
   // 解密
   let sm4 = require('sm-crypto').sm2;
   let doDecrypt = sm4.doDecrypt(encryptData, privateKey1, cipherMode);
-  alert('解密:'+doDecrypt)
+  alert('解密:' + doDecrypt)
   // 验签
   let sm5 = require('sm-crypto').sm2;
   let verifyResult = sm5.doVerifySignature(doDecrypt, sign, publicKey2) // 验签结果
-  alert('验签:'+verifyResult)
+  alert('验签:' + verifyResult)
 }
 
 // 加密:
@@ -309,16 +283,16 @@ export function doSign(msgString) {
   // 1 - C1C3C2;	0 - C1C2C3;	默认为1
   let cipherMode = 1
   // 签名
-  let sign = sm2.doSignature(msgString,privateKey1, { hash:true, der:true })
+  let sign = sm2.doSignature(msgString, privateKey1, {hash: true, der: true})
   return sign;
 }
 
 // 验签
-export function doVerifySignature(msgString,sigValueHex) {
+export function doVerifySignature(msgString, sigValueHex) {
   let sm2 = require('sm-crypto').sm2;
   // 1 - C1C3C2;	0 - C1C2C3;	默认为1
   let cipherMode = 1
   // 签名
-  let verifyResult = sm2.doVerifySignature(msgString, sigValueHex, publicKey2,{ hash:true, der:true }) // 验签结果
+  let verifyResult = sm2.doVerifySignature(msgString, sigValueHex, publicKey2, {hash: true, der: true}) // 验签结果
   return verifyResult;
 }

+ 1 - 1
ui/src/permission.js

@@ -17,7 +17,7 @@ router.beforeEach(async(to, from, next) => {
   // set page title
   document.title = getPageTitle(to.meta.title)
 
-  if (getBrowserToken()) {
+  if (sessionStorage.getItem('token')) {
     if (to.path === '/login') {
       // if is logged in, redirect to the home page
       next({ path: '/' })

+ 1 - 0
ui/src/utils/auth.js

@@ -11,5 +11,6 @@ export function setToken(token) {
 }
 
 export function removeToken() {
+  alert('移除token')
   return Cookies.remove(TokenKey)
 }

+ 52 - 28
ui/src/views/login/index.vue

@@ -13,7 +13,7 @@
           maxlength="20"
           @input="onUsernameChange"
         >
-          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
+          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon"/>
         </el-input>
       </el-form-item>
 
@@ -26,7 +26,7 @@
           tabindex="2"
           maxlength="20"
         >
-          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
+          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon"/>
         </el-input>
       </el-form-item>
 
@@ -39,7 +39,7 @@
           tabindex="3"
           maxlength="4"
         >
-          <svg-icon slot="prefix" icon-class="verifyCode" class="el-input__icon input-icon" />
+          <svg-icon slot="prefix" icon-class="verifyCode" class="el-input__icon input-icon"/>
         </el-input>
         <div class="login-code">
           <img :src="captchaUrl" @click="updateCaptcha" class="login-code-img"/>
@@ -55,10 +55,12 @@
           tabindex="4"
           maxlength="6"
         >
-          <svg-icon slot="prefix" icon-class="mailbox" class="el-input__icon input-icon" />
+          <svg-icon slot="prefix" icon-class="mailbox" class="el-input__icon input-icon"/>
         </el-input>
         <div class="mail-box">
-          <el-button type="success" size="small" @click.prevent="sendMailCode" :disabled="isMailSend">{{sendBtnText}}</el-button>
+          <el-button type="success" size="small" @click.prevent="sendMailCode" :disabled="isMailSend">
+            {{ sendBtnText }}
+          </el-button>
         </div>
       </el-form-item>
       <el-form-item style="width:100%;">
@@ -79,8 +81,6 @@
 
 <script>
 
-import {doEncrypt} from "@/main";
-
 export default {
   name: 'Login',
   data() {
@@ -93,9 +93,9 @@ export default {
         // 验证码
         verifyCode: '',
         // 邮箱验证码
-        mailbox:''
+        mailbox: ''
       },
-      verifyuuid:'',
+      verifyuuid: '',
       // 是否已经发送了验证码
       isMailSend: false,
       // 计时器对象
@@ -105,14 +105,24 @@ export default {
       // 文本
       sendBtnText: '点击发送邮箱',
       captchaUrl: '/getVerifyCode',
-      captchaText:'',
+      captchaText: '',
       loginRules: {
         /*  username: [{ required: true, trigger: 'blur', validator: validateUsername }],
           password: [{ required: true, trigger: 'blur', validator: validatePassword }]*/
-        username: [{required: true, trigger: 'blur',message: '请输入用户名'}],
-        password: [{required: true, trigger: 'blur',message: '请输入密码'}],
-        verifyCode: [{required: true, trigger: 'blur',message: '请输入验证码'},  { min: 4, max: 4, message: '请输入4位验证码', trigger: 'blur' }],
-        mailbox: [{required: true, trigger: 'blur',message: '请输入邮箱口令'},  { min: 6, max: 6, message: '请输入6位邮箱口令', trigger: 'blur' }]
+        username: [{required: true, trigger: 'blur', message: '请输入用户名'}],
+        password: [{required: true, trigger: 'blur', message: '请输入密码'}],
+        verifyCode: [{required: true, trigger: 'blur', message: '请输入验证码'}, {
+          min: 4,
+          max: 4,
+          message: '请输入4位验证码',
+          trigger: 'blur'
+        }],
+        mailbox: [{required: true, trigger: 'blur', message: '请输入邮箱口令'}, {
+          min: 6,
+          max: 6,
+          message: '请输入6位邮箱口令',
+          trigger: 'blur'
+        }]
       },
       loading: false,
       redirect: undefined
@@ -131,13 +141,13 @@ export default {
   },
   methods: {
     // 当账号变化时,重置发送按钮
-    onUsernameChange () {
+    onUsernameChange() {
       this.reset()
     },
     /**
      * 重置倒计时
      */
-    reset () {
+    reset() {
       // 重置按钮可用
       this.isMailSend = false
       // 重置文本内容
@@ -154,7 +164,7 @@ export default {
     /**
      * 倒计时
      */
-    countDown () {
+    countDown() {
       // 将setInterval()方法赋值给前面定义的timer计时器对象,等用clearInterval()方法时方便清空这个计时器对象
       this.timer = setInterval(() => {
         // 替换文本,用es6里面的``这个来创建字符串模板,让秒实时改变
@@ -169,7 +179,7 @@ export default {
     /**
      * 发送邮箱验证码
      */
-    sendMailCode () {
+    sendMailCode() {
       // 判断账户是否已经输入
       if (!this.loginForm.username) {
         this.$message.error('请输入账号')
@@ -186,7 +196,7 @@ export default {
       this.$axios.post(
         '/getMailCode', param,
       ).then((res) => {
-          this.$message.success('邮件发送成功')
+        this.$message.success('邮件发送成功')
       })
     },
     // 获取验证码
@@ -208,7 +218,7 @@ export default {
         if (valid) {
           this.loading = true
           let verifycodetemp = this.loginForm.verifyCode
-          if (this.captchaText.toLowerCase()!=verifycodetemp.toLowerCase()){
+          if (this.captchaText.toLowerCase() != verifycodetemp.toLowerCase()) {
             this.$message.error('验证码录入错误!')
             this.updateCaptcha()
             this.loading = false
@@ -221,19 +231,18 @@ export default {
           param.append('verifyuuid', this.verifyuuid)
           param.append('mailbox', this.loginForm.mailbox)
           this.$axios.post('/user/login', param).then((res) => {
-            const {data} = res
             // sessionStorage.setItem('token', data)
-            document.cookie = "token=" + data;
-            document.cookie = "user=".concat(this.loginForm.username)
-            sessionStorage.setItem('user', this.loginForm.username)
+            // document.cookie = "token=" + data;
+            // document.cookie = "user=".concat(this.loginForm.username)
+            sessionStorage.setItem('token', res.data)
             console.log('login user is :' + this.loginForm.username)
             this.$router.push('/')
             this.loading = false
           }).catch((error) => {
             // 登录失败刷新验证码
             this.updateCaptcha()
-            this.loginForm.verifyCode=''
-            this.loginForm.mailbox=''
+            this.loginForm.verifyCode = ''
+            this.loginForm.mailbox = ''
             this.reset()
             this.loading = false
           })
@@ -256,6 +265,7 @@ export default {
   background-image: url("../../assets/images/login-background.jpg");
   background-size: cover;
 }
+
 .title {
   margin: 0px auto 30px auto;
   text-align: center;
@@ -267,33 +277,42 @@ export default {
   background: #ffffff;
   width: 400px;
   padding: 25px 25px 5px 25px;
+
   .el-input {
     height: 38px;
+
     input {
       height: 38px;
     }
   }
+
   .input-icon {
     height: 39px;
     width: 14px;
     margin-left: 2px;
   }
 }
+
 .login-tip {
   font-size: 13px;
   text-align: center;
   color: #bfbfbf;
 }
+
 .login-code {
-  display: flex;  justify-content: center;  align-items: center;
+  display: flex;
+  justify-content: center;
+  align-items: center;
   width: 33%;
   height: 38px;
   float: right;
+
   img {
     cursor: pointer;
     vertical-align: middle;
   }
 }
+
 .el-login-footer {
   height: 40px;
   line-height: 40px;
@@ -306,15 +325,20 @@ export default {
   font-size: 12px;
   letter-spacing: 1px;
 }
+
 .login-code-img {
   height: 38px;
   width: 105px;
 }
+
 .mail-box {
-  display: flex;  justify-content: center;  align-items: center;
+  display: flex;
+  justify-content: center;
+  align-items: center;
   width: 36%;
   height: 38px;
   float: right;
+
   img {
     cursor: pointer;
     vertical-align: middle;