Commit f09116ec authored by 曹盼盼's avatar 曹盼盼

修改微信小程序授权登录的session_key在后端解密

parent ad771642
......@@ -24,10 +24,12 @@ import com.yeejoin.amos.feign.privilege.model.IdPasswordAuthModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
......@@ -39,12 +41,20 @@ import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.security.AlgorithmParameters;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.util.*;
import static com.mysql.cj.jdbc.interceptors.SessionAssociationInterceptor.getSessionKey;
@Service
@Slf4j
public class TzsAppService {
......@@ -112,6 +122,11 @@ public class TzsAppService {
RedisUtils redisUtils;
private static final String WxAppAppId ="wx48a1b1915b10d14b";
private static final String WxAppSecret="ac4f4a9d3c97676badb70c19a2f37b16";
private static final String WxAppGrantType="authorization_code";
@Value("${minio.url.path}")
String minioPath;
......@@ -127,20 +142,20 @@ public class TzsAppService {
/**
* 产品appkey
*/
private static final String appKey="AMOS_STUDIO";
private static final String appKey = "AMOS_STUDIO";
/**
* 产品product
*/
private static final String product="AMOS_STUDIO_WEB";
private static final String product = "AMOS_STUDIO_WEB";
private final int successsCode = 200;
public Map<String, Object> getEquipmentInfo(String record){
public Map<String, Object> getEquipmentInfo(String record) {
Map<String, Object> map = new HashMap();
map.put("SEQUENCE_NBR",record);
map.put("tableName","idx_biz_view_jg_claim");
map.put("SEQUENCE_NBR", record);
map.put("tableName", "idx_biz_view_jg_claim");
List<Map<String, Object>> detialMapList = equipmentCategoryServiceImpl.getTable(map).getRecords();
if (!ValidationUtil.isEmpty(detialMapList)){
if (!ValidationUtil.isEmpty(detialMapList)) {
map = detialMapList.iterator().next();
}
map.putAll(getQRCode(record));
......@@ -149,89 +164,89 @@ public class TzsAppService {
// 出厂
JSONObject exFactoryJsonObject = new JSONObject();
List exFactoryList = new ArrayList();
getGroupList(record, DesignInfo.class,DesignInfoModel.class, designInfoService, exFactoryList,false);
getGroupList(record, ProduceInfo.class,ProduceInfoModel.class, produceInfoService, exFactoryList,false);
exFactoryJsonObject.put("title","出厂");
exFactoryJsonObject.put("tabValue",exFactoryList);
getGroupList(record, DesignInfo.class, DesignInfoModel.class, designInfoService, exFactoryList, false);
getGroupList(record, ProduceInfo.class, ProduceInfoModel.class, produceInfoService, exFactoryList, false);
exFactoryJsonObject.put("title", "出厂");
exFactoryJsonObject.put("tabValue", exFactoryList);
jsonArray.add(exFactoryJsonObject);
// 施工
JSONObject constructionJsonObject = new JSONObject();
List constructionList = new ArrayList();
getGroupList(record, ConstructionInfo.class, ConstructionInfoModel.class, constructionInfoService, constructionList,true);
constructionJsonObject.put("title","施工");
constructionJsonObject.put("tabValue",constructionList);
getGroupList(record, ConstructionInfo.class, ConstructionInfoModel.class, constructionInfoService, constructionList, true);
constructionJsonObject.put("title", "施工");
constructionJsonObject.put("tabValue", constructionList);
jsonArray.add(constructionJsonObject);
// 注册
JSONObject registrationJsonObject = new JSONObject();
List registrationList = new ArrayList();
getGroupList(record, RegistrationInfo.class, RegistrationInfoModel.class, registrationInfoService, registrationList,false);
getGroupList(record, EquipTechParamBoiler.class, EquipTechParamBoilerModel.class, boilerService, registrationList,false);
getGroupList(record, EquipTechParamElevator.class, EquipTechParamElevatorModel.class, elevatorService, registrationList,false);
getGroupList(record, EquipTechParamLifting.class, EquipTechParamLiftingModel.class, elevatorService, registrationList,false);
getGroupList(record, EquipTechParamPipeline.class, EquipTechParamPipelineModel.class, pipelineService, registrationList,false);
getGroupList(record, EquipTechParamRides.class, EquipTechParamRidesModel.class, ridesService, registrationList,false);
getGroupList(record, EquipTechParamRopeway.class, EquipTechParamRopewayModel.class, ropewayService, registrationList,false);
getGroupList(record, EquipTechParamVehicle.class, EquipTechParamVehicleModel.class, vehicleService, registrationList,false);
getGroupList(record, EquipTechParamVessel.class, EquipTechParamVesselModel.class, vesselService, registrationList,false);
getGroupList(record, MainParts.class, MainPartsModel.class, mainPartsService, registrationList,false);
getGroupList(record, ProtectionDevices.class, ProtectionDevicesModel.class, protectionDevicesService, registrationList,false);
registrationJsonObject.put("title","注册");
registrationJsonObject.put("tabValue",registrationList);
getGroupList(record, RegistrationInfo.class, RegistrationInfoModel.class, registrationInfoService, registrationList, false);
getGroupList(record, EquipTechParamBoiler.class, EquipTechParamBoilerModel.class, boilerService, registrationList, false);
getGroupList(record, EquipTechParamElevator.class, EquipTechParamElevatorModel.class, elevatorService, registrationList, false);
getGroupList(record, EquipTechParamLifting.class, EquipTechParamLiftingModel.class, elevatorService, registrationList, false);
getGroupList(record, EquipTechParamPipeline.class, EquipTechParamPipelineModel.class, pipelineService, registrationList, false);
getGroupList(record, EquipTechParamRides.class, EquipTechParamRidesModel.class, ridesService, registrationList, false);
getGroupList(record, EquipTechParamRopeway.class, EquipTechParamRopewayModel.class, ropewayService, registrationList, false);
getGroupList(record, EquipTechParamVehicle.class, EquipTechParamVehicleModel.class, vehicleService, registrationList, false);
getGroupList(record, EquipTechParamVessel.class, EquipTechParamVesselModel.class, vesselService, registrationList, false);
getGroupList(record, MainParts.class, MainPartsModel.class, mainPartsService, registrationList, false);
getGroupList(record, ProtectionDevices.class, ProtectionDevicesModel.class, protectionDevicesService, registrationList, false);
registrationJsonObject.put("title", "注册");
registrationJsonObject.put("tabValue", registrationList);
jsonArray.add(registrationJsonObject);
// 使用
JSONObject useJsonObject = new JSONObject();
List useList = new ArrayList();
getGroupList(record, UseInfo.class, UseInfoModel.class, unseInfoService, useList,false);
useJsonObject.put("title","使用");
useJsonObject.put("tabValue",useList);
getGroupList(record, UseInfo.class, UseInfoModel.class, unseInfoService, useList, false);
useJsonObject.put("title", "使用");
useJsonObject.put("tabValue", useList);
jsonArray.add(useJsonObject);
// 维保
JSONObject maintenanceJsonObject = new JSONObject();
List maintenanceList = new ArrayList();
getGroupList(record, MaintenanceInfo.class, MaintenanceInfoModel.class, maintenanceInfoService, maintenanceList,true);
maintenanceJsonObject.put("title","维保");
maintenanceJsonObject.put("tabValue",maintenanceList);
getGroupList(record, MaintenanceInfo.class, MaintenanceInfoModel.class, maintenanceInfoService, maintenanceList, true);
maintenanceJsonObject.put("title", "维保");
maintenanceJsonObject.put("tabValue", maintenanceList);
jsonArray.add(maintenanceJsonObject);
// 检验
JSONObject inspectionJsonObject = new JSONObject();
List inspectionList = new ArrayList();
getGroupList(record, InspectionDetectionInfo.class, InspectionDetectionInfoModel.class, inspectionDetectionInfoService, inspectionList,true);
inspectionJsonObject.put("title","检验");
inspectionJsonObject.put("tabValue",inspectionList);
getGroupList(record, InspectionDetectionInfo.class, InspectionDetectionInfoModel.class, inspectionDetectionInfoService, inspectionList, true);
inspectionJsonObject.put("title", "检验");
inspectionJsonObject.put("tabValue", inspectionList);
jsonArray.add(inspectionJsonObject);
// 其他
JSONObject otherJsonObject = new JSONObject();
List otherList = new ArrayList();
getGroupList(record, OtherInfo.class, OtherInfoModel.class, otherInfoService, otherList,false);
otherJsonObject.put("title","其他");
otherJsonObject.put("tabValue",otherList);
getGroupList(record, OtherInfo.class, OtherInfoModel.class, otherInfoService, otherList, false);
otherJsonObject.put("title", "其他");
otherJsonObject.put("tabValue", otherList);
jsonArray.add(otherJsonObject);
map.put("tab",jsonArray);
map.put("tab", jsonArray);
return map;
}
public void getGroupList(String record,Class entity, Class dto, BaseService service, List list, boolean isOne){
public void getGroupList(String record, Class entity, Class dto, BaseService service, List list, boolean isOne) {
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""), entity);
QueryWrapper wrapper = new QueryWrapper();
wrapper.eq("RECORD",record);
if(isOne){
wrapper.eq("RECORD", record);
if (isOne) {
wrapper.orderByDesc("REC_DATE");
}
List entityList = service.list(wrapper);
Iterator iterator = entityList.iterator();
if(!isOne) {
if (!isOne) {
if (!ValidationUtil.isEmpty(entityList)) {
while (iterator.hasNext()) {
JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(iterator.next()));
JSONObject result = getFieldList(dto, jsonObject,null);
JSONObject result = getFieldList(dto, jsonObject, null);
list.add(result);
}
}
......@@ -239,56 +254,56 @@ public class TzsAppService {
} else {
int count = entityList.size();
JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(iterator.next()));
JSONObject result = getFieldList(dto, jsonObject,count);
JSONObject result = getFieldList(dto, jsonObject, count);
list.add(result);
}
}
public JSONObject getFieldList(Class clazz,JSONObject jsonObject,Integer count){
public JSONObject getFieldList(Class clazz, JSONObject jsonObject, Integer count) {
JSONObject result = new JSONObject();
JSONObject ApiModel = JSON.parseObject(JSON.toJSONString(clazz.getAnnotation(ApiModel.class)));
String groupName = ApiModel.getString("description");
Field[] declaredFields = clazz.getDeclaredFields();
List<Map<String,Object>> list = new ArrayList<>();
if(!ValidationUtil.isEmpty(declaredFields)){
List<Map<String, Object>> list = new ArrayList<>();
if (!ValidationUtil.isEmpty(declaredFields)) {
for (Field field : declaredFields) {
if (field.getAnnotation(ApiModelProperty.class) != null && !ValidationUtil.isEmpty(field.getAnnotation(ApiModelProperty.class).value())) {
Map<String,Object> map = new HashMap<>();
Map<String, Object> map = new HashMap<>();
String filedName = field.getAnnotation(ApiModelProperty.class).value();
// key和value可根据需求存
// 这存的key为注解的值,value为类属性名
map.put( "fieldName",filedName);
map.put("fieldValue",jsonObject.getString(field.getName()));
map.put("fieldKey",field.getName());
map.put("fieldName", filedName);
map.put("fieldValue", jsonObject.getString(field.getName()));
map.put("fieldKey", field.getName());
list.add(map);
}
}
}
// 整理出现多个附件的情况
Iterator<Map<String,Object>> iterator = list.iterator();
Iterator<Map<String, Object>> iterator = list.iterator();
JSONArray array = new JSONArray();
Boolean bool = true;
String name = "";
while (iterator.hasNext()) {
Map<String,Object> map = iterator.next();
Map<String, Object> map = iterator.next();
String fieldName = map.get("fieldName").toString();
if(fieldName.contains("附件")){
if(bool){
if (fieldName.contains("附件")) {
if (bool) {
// 第一个出现的附件名称为表单显示的名称
name = fieldName;
bool = false;
}
if(!ValidationUtil.isEmpty(map.get("fieldValue"))){
if (!ValidationUtil.isEmpty(map.get("fieldValue"))) {
JSONArray jsonArray = JSON.parseArray(String.valueOf(map.get("fieldValue")));
JSONArray json = new JSONArray();
for(Object obj: jsonArray){
for (Object obj : jsonArray) {
JSONObject object = JSON.parseObject(JSON.toJSONString(obj));
if(!ValidationUtil.isEmpty(object)){
if (!ValidationUtil.isEmpty(object)) {
object.getString("url");
object.put("url",minioPath+object.getString("url"));
object.put("url", minioPath + object.getString("url"));
json.add(object);
}
}
......@@ -299,7 +314,7 @@ public class TzsAppService {
}
}
// 如果有附件 整理为一个附件 添加入list里
if(!bool) {
if (!bool) {
Map<String, Object> map = new HashMap<>();
map.put("fieldKey", "files");
map.put("fieldValue", array);
......@@ -307,33 +322,34 @@ public class TzsAppService {
list.add(map);
}
if(!ValidationUtil.isEmpty(count)){
result.put("groupCount",count);
if (!ValidationUtil.isEmpty(count)) {
result.put("groupCount", count);
}
result.put("groupName",ApiModel.getString("description"));
result.put("groupKey",ApiModel.getString("value"));
result.put("groupValue",list);
result.put("groupName", ApiModel.getString("description"));
result.put("groupKey", ApiModel.getString("value"));
result.put("groupValue", list);
return result;
}
/**
* 获取焊口编号
*
* @return
*/
public JSONObject getQRCode(String code){
public JSONObject getQRCode(String code) {
String url = "";
JSONObject jsonObject = new JSONObject();
byte[] bytes = QRCodeUtil.generateQRCodeImageByteData(code,50);
byte[] bytes = QRCodeUtil.generateQRCodeImageByteData(code, 50);
InputStream inputStream = new ByteArrayInputStream(bytes);
try {
MultipartFile file = new MockMultipartFile(code+".jpg",code+".jpg", ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
MultipartFile file = new MockMultipartFile(code + ".jpg", code + ".jpg", ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
FeignClientResult<Map<String, String>> date = Systemctl.fileStorageClient.updateCommonFileFree(file, "ugp/qrcode");
if (date != null) {
Map<String, String> map = date.getResult();
Iterator<String> it = map.keySet().iterator();
String urlString=it.next();
jsonObject.put("fileUrl", minioPath+urlString);
String urlString = it.next();
jsonObject.put("fileUrl", minioPath + urlString);
jsonObject.put("fileName", code);
}
} catch (IOException e) {
......@@ -347,8 +363,8 @@ public class TzsAppService {
return ObjectUtils.isEmpty(categoryOtherInfo) ? null : getEquipmentInfo(categoryOtherInfo.getRecord());
}
public Map<String, Object> login(MobileLoginParam param){
public Map<String, Object> login(MobileLoginParam param) {
Map<String, Object> result = new LinkedHashMap<>();
IdPasswordAuthModel idPasswordAuthModel = new IdPasswordAuthModel();
idPasswordAuthModel.setLoginId(param.getPhoneNo());
......@@ -358,7 +374,7 @@ public class TzsAppService {
RequestContext.setProduct(product);
RequestContext.setAppKey(appKey);
try {
idpassword = Privilege.authClient.idpassword(idPasswordAuthModel);
idpassword = Privilege.authClient.idpassword(idPasswordAuthModel);
} catch (Exception e) {
e.printStackTrace();
}
......@@ -393,42 +409,53 @@ public class TzsAppService {
}
@SneakyThrows
public JSONObject wxUserLogin(JSONObject wx) {
/* if (redisUtils.hasKey(WXUSER_TOKEN)) {
Object obj= redisUtils.get(WXUSER_TOKEN);
return JSONObject.parseObject(obj.toString());
}else {
StringBuffer buffer= new StringBuffer("https://api.weixin.qq.com/sns/jscode2session?appid=")
.append(wx.getString("appid")).append("&secret=").append(wx.getString("secret")).append("&js_code=").append(wx.getString("js_code"))
.append("&grant_type=").append( wx.getString("grant_type"));
String responseStr = HttpUtils.doGet(buffer.toString());
JSONObject response = null;
try {
response = JSONObject.parseObject(responseStr);
System.out.println("666"+response.getString("session_key"));
} catch (Exception e) {
throw new BadRequest("session_key 出错:" + e.getMessage());
JSONObject obj = getSessionKey(wx);
String sessionKey = obj.getString("session_key");
//被加密的数据
byte[] dataByte = Base64.getDecoder().decode(wx.getString("encryptedData"));
//加密秘钥
byte[] keyByte = Base64.getDecoder().decode(sessionKey);
//偏移量
byte[] ivByte = Base64.getDecoder().decode(wx.getString("iv"));
JSONObject res=null;
// 如果密钥不足16位,那么就补足. 这个if 中的内容很重要
int base = 16;
if (keyByte.length % base != 0) {
int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
byte[] temp = new byte[groups * base];
Arrays.fill(temp, (byte) 0);
System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
keyByte = temp;
}
if(response.get("session_key") != null) { // 获取token 成功
try {
redisUtils.set(WXUSER_TOKEN, response,time);
return response;
} catch (Exception e) {
throw new BadRequest("session_key 出错:" + e.getMessage());
}
} else {
throw new BadRequest("session_key 出错:" + response);
// 初始化
Security.addProvider(new BouncyCastleProvider());
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
parameters.init(new IvParameterSpec(ivByte));
cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
byte[] resultByte = cipher.doFinal(dataByte);
if (null != resultByte && resultByte.length > 0) {
String result = new String(resultByte, "UTF-8");
res=JSONObject.parseObject(result);
return res ;
}
}*/
return res;
}
StringBuffer buffer= new StringBuffer("https://api.weixin.qq.com/sns/jscode2session?appid=")
.append(wx.getString("appid")).append("&secret=").append(wx.getString("secret")).append("&js_code=").append(wx.getString("js_code"))
.append("&grant_type=").append( wx.getString("grant_type"));
private JSONObject getSessionKey(JSONObject wx) {
StringBuffer buffer = new StringBuffer("https://api.weixin.qq.com/sns/jscode2session?appid=")
.append(WxAppAppId).append("&secret=").append(WxAppSecret).append("&js_code=").append(wx.getString("js_code"))
.append("&grant_type=").append(WxAppGrantType);
String responseStr = HttpUtils.doGet(buffer.toString());
JSONObject response=JSONObject.parseObject(responseStr);
JSONObject response = JSONObject.parseObject(responseStr);
return response;
}
}
spring.application.name=TZS
spring.application.name=TZS-cpp
server.servlet.context-path=/tzs
server.port=11000
spring.profiles.active=dev3
......@@ -163,4 +163,8 @@ spring.main.allow-bean-definition-overriding=true
is.ugp=false
#\u5DE5\u4F5C\u53F0\u7528\u6237\u7EDF\u4E00\u663E\u793A\u5934\u50CF
tzs.auth.user.photo=/public/common/userPic.png
\ No newline at end of file
tzs.auth.user.photo=/public/common/userPic.png
tzs.WxApp.appId=wx48a1b1915b10d14b
tzs.WxApp.secret=ac4f4a9d3c97676badb70c19a2f37b16
tzs.WxApp.grant-type=authorization_code
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment