Forráskód Böngészése

将jwt的编码解码统一放置到JwtUtil

tomatozq 5 éve
szülő
commit
782597ac3d

+ 1 - 1
web/src/main/java/com/jpsoft/smart/config/WebMvcConfig.java

@@ -67,6 +67,6 @@ public class WebMvcConfig implements WebMvcConfigurer {
 				.excludePathPatterns("/mobile/personInfoApi/validateCode")
 				.excludePathPatterns("/mobile/personInfoApi/findByOpenId")
 				.excludePathPatterns("/mobile/personDeviceLogApi/detail")
-		;
+				.excludePathPatterns("/mobile/PersonDeviceFilterLog/queryUnmeasureGroupList");
 	}
 }

+ 2 - 19
web/src/main/java/com/jpsoft/smart/interceptor/LoginInterceptor.java

@@ -2,6 +2,7 @@ package com.jpsoft.smart.interceptor;
 
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.jpsoft.smart.modules.common.dto.MessageResult;
+import com.jpsoft.smart.modules.common.utils.JwtUtil;
 import io.jsonwebtoken.Claims;
 import io.jsonwebtoken.Jwts;
 import io.jsonwebtoken.security.Keys;
@@ -35,30 +36,12 @@ public class LoginInterceptor implements HandlerInterceptor {
 
         if (StringUtils.isEmpty(token)) {
             token = request.getParameter("token");
-            token = URLDecoder.decode(token,"UTF-8");
         }
 
         boolean result = false;
 
         try {
-            String prefix = "Bearer ";
-
-            if (token==null || token.length() < prefix.length()){
-                throw new Exception("未传递令牌或未带前缀Bearer!");
-            }
-
-            token = token.substring(prefix.length());
-
-            byte[] privateKey = Base64.getDecoder().decode(jwtSecret);
-
-            Key key = Keys.hmacShaKeyFor(privateKey);
-
-            Claims claims = Jwts.parser()
-                            .setSigningKey(key)
-                            .parseClaimsJws(token)
-                            .getBody();
-
-            String userId = claims.getSubject();
+            String userId = JwtUtil.decodeToken(jwtSecret,token);
 
             request.setAttribute("subject",userId);
 

+ 5 - 21
web/src/main/java/com/jpsoft/smart/modules/common/controller/JwtsUserController.java

@@ -2,13 +2,13 @@ package com.jpsoft.smart.modules.common.controller;
 
 import com.jpsoft.smart.modules.common.dto.MessageResult;
 import com.jpsoft.smart.modules.common.utils.DES3;
+import com.jpsoft.smart.modules.common.utils.JwtUtil;
 import com.jpsoft.smart.modules.sys.entity.User;
 import com.jpsoft.smart.modules.sys.service.UserService;
-import io.jsonwebtoken.Jwts;
-import io.jsonwebtoken.security.Keys;
 import io.swagger.annotations.ApiImplicitParam;
 import io.swagger.annotations.ApiImplicitParams;
 import io.swagger.annotations.ApiOperation;
+import org.joda.time.DateTime;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.web.bind.annotation.GetMapping;
@@ -16,11 +16,7 @@ import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RequestAttribute;
 import org.springframework.web.bind.annotation.RestController;
 import springfox.documentation.annotations.ApiIgnore;
-
 import javax.servlet.http.HttpSession;
-import java.security.Key;
-import java.util.Base64;
-import java.util.Date;
 
 @RestController
 public class JwtsUserController {
@@ -47,23 +43,11 @@ public class JwtsUserController {
             String passwordEnc = des3.encrypt(jwtSecret,password);
 
             if(user!=null && passwordEnc.equals(user.getPassword())){
-                //生成token
-                Date now = new Date();
-                long expiration = now.getTime() + 3600 * 6000; //6个小时后,该客户端的token过期
-
-                byte[] privateKey = Base64.getDecoder().decode(jwtSecret);
 
-                Key key = Keys.hmacShaKeyFor(privateKey);
-
-                String token = Jwts.builder()
-                        .setSubject(user.getId())
-                        //设置自定义claims后,setSubject值将失效
-//               .setClaims(extraInfo)
-                        .signWith(key)
-                        .setExpiration(new Date(expiration))
-                        .compact();
+                //生成token
+                String token = JwtUtil.createToken(jwtSecret,user.getId(),DateTime.now().plusHours(6).toDate());
 
-                session.setAttribute("token","Bearer " + token);
+                session.setAttribute("token",token);
 
                 messageResult.setResult(true);
                 messageResult.setData("Bearer " + token);

+ 51 - 0
web/src/main/java/com/jpsoft/smart/modules/common/utils/JwtUtil.java

@@ -0,0 +1,51 @@
+package com.jpsoft.smart.modules.common.utils;
+
+import io.jsonwebtoken.Claims;
+import io.jsonwebtoken.Jwts;
+import io.jsonwebtoken.security.Keys;
+
+import java.security.Key;
+import java.util.Base64;
+import java.util.Date;
+
+public class JwtUtil {
+    public static String createToken(String jwtSecret, String subject, Date expiration) {
+        //token有效时间天
+        byte[] privateKey = Base64.getDecoder().decode(jwtSecret);
+
+        Key key = Keys.hmacShaKeyFor(privateKey);
+
+        String token = Jwts.builder()
+                    .setSubject(subject)
+                //设置自定义claims后,setSubject值将失效
+//               .setClaims(extraInfo)
+                    .signWith(key)
+                    .setExpiration(expiration)
+                    .compact();
+
+        return "Bearer " + token;
+    }
+
+    public static String decodeToken(String jwtSecret,String token) throws Exception{
+        String prefix = "Bearer ";
+
+        if (token==null || token.length() < prefix.length()){
+            throw new Exception("未传递令牌或未带前缀Bearer!");
+        }
+
+        token = token.substring(prefix.length());
+
+        byte[] privateKey = Base64.getDecoder().decode(jwtSecret);
+
+        Key key = Keys.hmacShaKeyFor(privateKey);
+
+        Claims claims = Jwts.parser()
+                .setSigningKey(key)
+                .parseClaimsJws(token)
+                .getBody();
+
+        String subject = claims.getSubject();
+
+        return subject;
+    }
+}

+ 12 - 5
web/src/main/java/com/jpsoft/smart/modules/mobile/controller/PersonDeviceFilterLogController.java

@@ -6,6 +6,7 @@ import com.jpsoft.smart.modules.base.entity.*;
 import com.jpsoft.smart.modules.base.service.*;
 import com.jpsoft.smart.modules.common.dto.MessageResult;
 import com.jpsoft.smart.modules.common.dto.Sort;
+import com.jpsoft.smart.modules.common.utils.JwtUtil;
 import com.jpsoft.smart.modules.common.utils.PojoUtils;
 import io.swagger.annotations.ApiImplicitParam;
 import io.swagger.annotations.ApiImplicitParams;
@@ -15,16 +16,21 @@ import org.joda.time.DateTime;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.format.annotation.DateTimeFormat;
 import org.springframework.web.bind.annotation.*;
 
 import java.math.BigDecimal;
+import java.net.URLDecoder;
 import java.text.SimpleDateFormat;
 import java.util.*;
 
 @RestController
 @RequestMapping("/mobile/PersonDeviceFilterLog")
 public class PersonDeviceFilterLogController {
+    @Value("${jwt.secret}")
+    private String jwtSecret;
+
     private Logger logger = LoggerFactory.getLogger(getClass());
 
     @Autowired
@@ -168,22 +174,23 @@ public class PersonDeviceFilterLogController {
             @ApiImplicitParam(name="companyId",value = "公司编号",required = false,paramType = "form"),
             @ApiImplicitParam(name = "queryDate",value = "查询日期(yyyy-MM-dd)",required = true, paramType = "form"),
             @ApiImplicitParam(name="alarmConfigId",value = "考勤设置编号",required = false,paramType = "form"),
-            @ApiImplicitParam(name="token",value = "令牌",required = true,paramType = "form"),
-            @ApiImplicitParam(name="subject",value = "目标(不传)",paramType = "form")
+            @ApiImplicitParam(name="token",value = "令牌",required = false,paramType = "form")
     })
     public MessageResult<Map> queryUnmeasureGroupList(
             String companyId,
             @DateTimeFormat(pattern = "yyyy-MM-dd") Date queryDate,
             String alarmConfigId,
-            @RequestAttribute String subject,
             String token){
         MessageResult<Map> msgResult = new MessageResult<>();
         Map<String,Object> dataMap = new HashMap<>();
 
         try{
-            PersonInfo personInfo = personInfoService.get(Long.valueOf(subject));
-
             if (StringUtils.isEmpty(companyId)){
+                token = URLDecoder.decode(token,"UTF-8");
+
+                String subject = JwtUtil.decodeToken(jwtSecret,token);
+
+                PersonInfo personInfo = personInfoService.get(Long.valueOf(subject));
                 companyId = personInfo.getCompanyId();
             }
 

+ 5 - 25
web/src/main/java/com/jpsoft/smart/modules/mobile/controller/PersonInfoApiController.java

@@ -10,10 +10,7 @@ import com.jpsoft.smart.modules.base.service.PersonDeviceRelationService;
 import com.jpsoft.smart.modules.base.service.PersonInfoService;
 import com.jpsoft.smart.modules.common.dto.MessageResult;
 import com.jpsoft.smart.modules.common.dto.Sort;
-import com.jpsoft.smart.modules.common.utils.CheckIdCard;
-import com.jpsoft.smart.modules.common.utils.OSSUtil;
-import com.jpsoft.smart.modules.common.utils.PojoUtils;
-import com.jpsoft.smart.modules.common.utils.SMSUtil;
+import com.jpsoft.smart.modules.common.utils.*;
 import com.jpsoft.smart.modules.lapi.service.ILapiService;
 import com.jpsoft.smart.modules.lapi.vo.LapiMsgResult;
 import com.jpsoft.smart.modules.sys.entity.User;
@@ -25,6 +22,7 @@ import io.swagger.annotations.ApiImplicitParams;
 import io.swagger.annotations.ApiOperation;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.poi.ss.formula.functions.T;
+import org.joda.time.DateTime;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.amqp.rabbit.core.RabbitTemplate;
@@ -116,7 +114,7 @@ public class PersonInfoApiController {
             }
 
             Map<String,Object> dataMap = new HashMap<String, Object>();
-            String token = createToken(personInfo.getId());
+            String token = JwtUtil.createToken(jwtSecret,personInfo.getId() +"", DateTime.now().plusHours(6).toDate());
 
             dataMap.put("person",personInfo);
             dataMap.put("token", token);
@@ -205,7 +203,7 @@ public class PersonInfoApiController {
                 personInfoService.update(personInfo);
             }
 
-            String token = createToken(personId);
+            String token = JwtUtil.createToken(jwtSecret,String.valueOf(personId), DateTime.now().plusHours(6).toDate());
 
             messageResult.setData(token);
             messageResult.setResult(true);
@@ -219,24 +217,6 @@ public class PersonInfoApiController {
         return messageResult;
     }
 
-    private String createToken(Long personId) {
-        //token有效时间2小时
-        byte[] privateKey = Base64.getDecoder().decode(jwtSecret);
-
-        Date now = new Date();
-        long expiration = now.getTime() + 3600 * 6000; //6个小时后,该客户端的token过期
-
-        Key key = Keys.hmacShaKeyFor(privateKey);
-
-        String token = Jwts.builder()
-                .setSubject(personId + "")
-                .signWith(key)
-                .setExpiration(new Date(expiration))
-                .compact();
-
-        return "Bearer " + token;
-    }
-
     @PostMapping("upload")
     @ApiOperation(value="人员照片上传")
     @ApiImplicitParams({
@@ -252,7 +232,7 @@ public class PersonInfoApiController {
         try {
             PersonInfo personInfo = personInfoService.get(Long.valueOf(subject));
 
-            if (personInfo==null){
+            if (personInfo==    null){
                 throw new Exception("人员信息不存在!");
             }
 

+ 6 - 19
web/src/main/java/com/jpsoft/smart/schduled/UnmeasureTemperatureAlarmTask.java

@@ -6,6 +6,7 @@ import com.jpsoft.smart.modules.base.entity.*;
 import com.jpsoft.smart.modules.base.service.*;
 import com.jpsoft.smart.modules.business.entity.WorkAttendance;
 import com.jpsoft.smart.modules.business.service.WorkAttendanceService;
+import com.jpsoft.smart.modules.common.utils.JwtUtil;
 import com.jpsoft.smart.modules.common.utils.OSSUtil;
 import com.jpsoft.smart.modules.common.utils.POIUtils;
 import com.jpsoft.smart.modules.common.utils.WechatMessageUtil;
@@ -348,24 +349,6 @@ public class UnmeasureTemperatureAlarmTask {
         }
     }
 
-    private String createToken(Long personId) {
-        //token有效时间2小时
-        byte[] privateKey = Base64.getDecoder().decode(jwtSecret);
-
-        Date now = new Date();
-        long expiration = now.getTime() + 3600 * 6000; //6个小时后,该客户端的token过期
-
-        Key key = Keys.hmacShaKeyFor(privateKey);
-
-        String token = Jwts.builder()
-                .setSubject(personId + "")
-                .signWith(key)
-                .setExpiration(new Date(expiration))
-                .compact();
-
-        return "Bearer " + token;
-    }
-
     @Async
     public void noticeManager(AlarmConfig alarmConfig, DateTime startTime, DateTime endTime) {
         CompanyInfo companyInfo = companyInfoService.get(alarmConfig.getCompanyId());
@@ -405,7 +388,11 @@ public class UnmeasureTemperatureAlarmTask {
                 }
 
                 try {
-                    String url = unMeasureUrl + "?token=" + URLEncoder.encode(createToken(personId), "UTF-8");
+                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+
+                    String token = JwtUtil.createToken(jwtSecret,String.valueOf(personId),sdf.parse("2030-01-01"));
+
+                    String url = unMeasureUrl + "?token=" + URLEncoder.encode(token,"UTF-8");
                     url += "&companyId=" + alarmConfig.getCompanyId();
                     url += "&queryDate=" + startTime.toString("yyyy-MM-dd");
                     url += "&alarmConfigId=" + alarmConfig.getId();