Commit f9a7aab3 by guominglei

修改获取当前用户信息修改

parent 54cbd841
......@@ -79,6 +79,9 @@ public class ApiFlowServiceImpl implements ApiFlowService {
@Resource
private WaitingTaskMapper waitingTaskMapper;
@Resource
private CurrentUserUtils currentUserUtils;
private void parseParam(String param, String workspaceName, String flowName){
ValidationUtil.dataNotBank(param, "请求参数不允许为空!");
JSONObject jsonObject = JSON.parseObject(param);
......@@ -454,7 +457,7 @@ public class ApiFlowServiceImpl implements ApiFlowService {
JobTaskRunLog jobTaskRunLog = jobTaskRunLogMapper.findByRunIdAndNodeId(runInfo.getRunId(), node.getNodeId());
ValidationUtil.dataNotNull(jobTaskRunLog, "查无此运行记录");
String userName = CurrentUserUtils.userName();
String userName = currentUserUtils.account();
//校验上级是否成功
List<Integer> dependNodeList = nodeDependencyMapper.findDependIdByNodeId(node.getNodeId());
......@@ -534,7 +537,7 @@ public class ApiFlowServiceImpl implements ApiFlowService {
List<JobTask> jobTaskList = new ArrayList<>();
List<Node> nodeList = nodeMapper.findOnforkByFlowId(flow.getFlowId());
ValidationUtil.dataNotNull(nodeList, "该工作流没有在调度上的任务");
String userName = CurrentUserUtils.userName();
String userName = currentUserUtils.account();
nodeList.forEach(node -> {
JobTask jobTask = new JobTask();
BeanUtils.copyProperties(node, jobTask);
......@@ -748,7 +751,7 @@ public class ApiFlowServiceImpl implements ApiFlowService {
if (order == null){
order = 0;
}
String userName = CurrentUserUtils.userName();
String userName = currentUserUtils.account();
for (String repairTime : repairTimeList){
WaitingRecord waitingRecord = new WaitingRecord();
RunRecording runRecording = new RunRecording();
......@@ -780,7 +783,7 @@ public class ApiFlowServiceImpl implements ApiFlowService {
private Map<String, List<WaitingTask>> buildTask(List<Node> nodeList, List<String> nodeNameList, List<String> repairTimeList){
Map<String, List<WaitingTask>> result = new HashMap<>();
String usernName = CurrentUserUtils.userName();
String usernName = currentUserUtils.account();
List<WaitingTask> waitingTaskList = new ArrayList<>();
nodeList.forEach(node -> {
WaitingTask waitingTask = new WaitingTask();
......
......@@ -26,6 +26,12 @@ logging:
path: /data/mythjob
file: myth_log_file
authentication:
user:
header-name: token
expire: 43200 # 外部token有效期为12小时
pub-key: client/pub.key # 解密
file:
system:
ip: 10.0.120.2
......
......@@ -26,6 +26,12 @@ logging:
path: /data/mythjob
file: myth_log_file
authentication:
user:
header-name: token
expire: 43200 # 外部token有效期为12小时
pub-key: client/pub.key # 解密
file:
system:
ip: 10.0.120.2
......
......@@ -26,6 +26,12 @@ logging:
path: /data/mythjob
file: myth_log_file
authentication:
user:
header-name: token
expire: 43200 # 外部token有效期为12小时
pub-key: client/pub.key # 解密
file:
system:
ip: 10.0.120.2
......
......@@ -26,6 +26,12 @@ logging:
path: /data/mythjob
file: myth_log_file
authentication:
user:
header-name: token
expire: 43200 # 外部token有效期为12小时
pub-key: client/pub.key # 解密
file:
system:
ip: ${FILE_IP}
......
package com.byit.job.utils;
/**
* 常量工具类
*
* @author liyuan
*/
public class BaseContextConstants {
/**
*
*/
public static final String TOKEN_NAME = "token";
/**
*
*/
public static final String JWT_KEY_USER_ID = "userid";
/**
*
*/
public static final String JWT_KEY_NAME = "name";
/**
*
*/
public static final String JWT_KEY_ACCOUNT = "account";
/**
* 组织id
*/
public static final String JWT_KEY_ORG_ID = "orgid";
/**
* 岗位id
*/
public static final String JWT_KEY_STATION_ID = "stationid";
/**
* 租户
*/
public static final String TENANT = "tenant";
public static final String IS_BOOT = "boot";
/**
* 动态数据库名前缀。 每个项目配置死的
*/
public static final String DATABASE_NAME = "database_name";
}
package com.byit.job.utils;
import com.byit.dto.common.UserInfo;
import com.byit.dto.common.JwtUserInfo;
import com.byit.utils.ValidationUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
@Component
public class CurrentUserUtils {
public static UserInfo getCurrentUser() {
@Value("{authentication.user.pub-key}")
private String pubKey;
public JwtUserInfo getCurrentUser() {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (servletRequestAttributes != null) {
HttpServletRequest request = servletRequestAttributes.getRequest();
String token = request.getHeader("token");
ValidationUtil.dataNotBank(token,"token为空");
TokenHelper tokenHelper = new TokenHelper();
UserInfo userInfo = tokenHelper.parseToken(token);
JwtUserInfo userInfo = JwtHelper.getJwtFromToken(token, pubKey);
return userInfo;
}
return null;
}
public static String userName() {
return getCurrentUser().getUserName();
public String account() {
return getCurrentUser().getAccount();
}
}
package com.byit.job.utils;
import com.byit.dto.common.JwtUserInfo;
import com.byit.job.exceptions.BusinessException;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
/**
* Created by ace on 2017/9/10.
*/
@Slf4j
public class JwtHelper {
private static final RsaKeyHelper RSA_KEY_HELPER = new RsaKeyHelper();
/**
* 获取token中的用户信息
*
* @param token token
* @param pubKeyPath 公钥路径
* @return
*/
public static JwtUserInfo getJwtFromToken(String token, String pubKeyPath) {
Jws<Claims> claimsJws = parserToken(token, pubKeyPath);
Claims body = claimsJws.getBody();
String strUserId = body.getSubject();
String account = String.valueOf(body.get(BaseContextConstants.JWT_KEY_ACCOUNT));
String name = String.valueOf(body.get(BaseContextConstants.JWT_KEY_NAME));
String strOrgId = String.valueOf(body.get(BaseContextConstants.JWT_KEY_ORG_ID));
String strDepartmentId = String.valueOf(body.get(BaseContextConstants.JWT_KEY_STATION_ID));
Long userId = Long.valueOf(strUserId);
Long orgId = Long.valueOf(strOrgId);
Long departmentId = Long.valueOf(strDepartmentId);
return new JwtUserInfo(userId, account, name, orgId, departmentId);
}
/**
* 公钥解析token
*
* @param token
* @param pubKeyPath 公钥路径
* @return
* @throws Exception
*/
private static Jws<Claims> parserToken(String token, String pubKeyPath) {
try {
return Jwts.parser().setSigningKey(RSA_KEY_HELPER.getPublicKey(pubKeyPath)).parseClaimsJws(token);
} catch (ExpiredJwtException ex) {
//过期
throw new BusinessException("会话超时,请重新登录");
} catch (SignatureException ex) {
//签名错误
throw new BusinessException("不合法的token,请认真比对 token 的签名");
} catch (IllegalArgumentException ex) {
//token 为空
throw new BusinessException("缺少token参数");
} catch (Exception e) {
log.error(" message:{}", e.getMessage());
throw new BusinessException("解析token失败");
}
}
}
package com.byit.job.utils;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
/**
* Rsa key 帮助类
* Created by ace on 2017/9/10.
*/
public class RsaKeyHelper {
/**
* 获取公钥,用于解析token
*
* @param filename
* @return
* @throws Exception
*/
public PublicKey getPublicKey(String filename) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(filename);
try (DataInputStream dis = new DataInputStream(resourceAsStream)) {
byte[] keyBytes = new byte[resourceAsStream.available()];
dis.readFully(keyBytes);
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
}
/**
* 获取密钥 用于生成token
*
* @param filename
* @return
* @throws Exception
*/
public PrivateKey getPrivateKey(String filename) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(filename);
try (DataInputStream dis = new DataInputStream(resourceAsStream)) {
byte[] keyBytes = new byte[resourceAsStream.available()];
dis.readFully(keyBytes);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(spec);
}
}
}
package com.byit.job.utils;
import com.alibaba.fastjson.JSON;
import com.byit.dto.common.UserInfo;
import com.byit.utils.ValidationUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
public class TokenHelper {
private static String secretKey = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhYmMiLCJhdWQiOiIx";
private static int jwtTimeout = 36000;
public String generateToken(UserInfo user) {
return Jwts.builder()
.setSubject(JSON.toJSONString(user))
.setAudience("auth-center")
.setIssuedAt(new Date())
//.setExpiration(DateTime.now().plusSeconds(jwtTimeout).toDate())
.signWith(SignatureAlgorithm.HS512, secretKey)
.compact();
}
public UserInfo parseToken(String token) {
Claims claims = null;
UserInfo userInfo = new UserInfo();
try {
claims = Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(token)
.getBody();
} catch (ExpiredJwtException e) {
throw new RuntimeException("token已过期");
}
ValidationUtil.dataNotNull(claims, "未获取到token");
String subject = claims.getSubject();
ValidationUtil.dataNotBank(subject,"主题为空");
return JSON.parseObject(subject,UserInfo.class);
}
public boolean isExpire(String token) {
Claims claims = Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(token)
.getBody();
return new Date().before(claims.getExpiration());
}
}
\ No newline at end of file
package com.byit.dto.common;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* jwt 存储的 内容
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class JwtUserInfo implements Serializable {
/**
* 账号id
*/
private Long userId;
/**
* 账号
*/
private String account;
/**
* 姓名
*/
private String name;
/**
* 当前登录人单位id
*/
private Long orgId;
/**
* 当前登录人岗位ID
*/
private Long stationId;
}
package com.byit.dto.common;
import lombok.Data;
import java.io.Serializable;
@Data
public class UserInfo implements Serializable {
/**
* 用户ID
*/
private Integer userId;
/**
* 用户中文名
*/
private String nickName;
/**
* 用户名
*/
private String userName;
}
\ No newline at end of file
......@@ -14,7 +14,7 @@ myth-rpc:
registry:
address: http://localhost:8080/myth-register
biz: byit-myth-job
env: dev
env: gml
remoting:
port: 8082
......@@ -25,8 +25,8 @@ spring:
idle-timeout: 60000
maximum-pool-size: 5
minimum-idle: 1
password: root
url: jdbc:mysql://10.0.120.30:3307/myth-registry?useUnicode=true&useSSL=true&characterEncoding=utf-8&mysqlEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=false&autoReconnect=true&failOverReadOnly=false
password: 123456
url: jdbc:mysql://10.0.10.118:3306/myth-registry?Unicode=true&characterEncoding=UTF-8&useSSL=true
username: root
zuul:
route:
......
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