一,登录
- 首先在system模块提供一个统一的接口,入参为一个用户名,出参是该用户的所有信息,包括用户名,密码,以及该用户在每个公司所有的角色,以及权限信息,可将反参缓存入NOSQL数据库中
- 在登录模块中先去缓存中获取看该用户的用户信息是否有缓存,有的话,直接返回,没有的话远程调用上述1的接口获取吗,然后通过返回的信息和登录接口的信息进行对比校验,如果都正确,通过jwt工具返回token
二,用户权限校验,用户认证信息存储
(1)通过全局拦截器,及网关设计
- 首先网关会拦截所有的请求,然后我们可以在网关模块定义一个放行白名单,比如一些登录接口,引用swagger页面的接口进行放行
- 拦截下来的接口,我们去获取它的请求头看是否有token,没有的话,直接返回未授权
- 有的话继续下边的操作,解析token,通过解析出来的用户信息,通过用户名从system获取该用户的所有信息
- 然后先校验token中解析出来的密码与system查询出来的密码是否一致
- 如果一致,再进行下一步鉴权,通过system查询出来的用户信息,查询该用户在所有公司所有的权限信息,然后和当前请求的权限信息进行对比,如果发现当前请求url与查询出来的所有的url都不匹配,则返回未授权,若匹配,则将登录认证信息,比如用户名,密码,公司信息,若有多语种,还可添加语言等加入请求头中
代码如下:包括如何定义过滤器,以及上述操作
定义过滤器:
package sca.pro.gateway.common.auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
/**
* @author shq
* @description 自定义token认证过滤器工厂
* @createDate 2022-5-25
* @updateUser
* @updateDate
* @updateRemark
*/
@Component
public class AuthGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {
@Autowired
private AuthGatewayFilter authGatewayFilter;
@Override
public GatewayFilter apply(Object config) {
return authGatewayFilter;
}
}
package sca.pro.gateway.common.auth;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import sca.pro.common.contants.Contants;
import sca.pro.common.redis.authInfo.AuthInfo;
import sca.pro.common.redis.authInfo.CompanyInfo;
import sca.pro.common.response.HttpCode;
import sca.pro.common.response.HttpResult;
import sca.pro.common.utils.PasswordUtils;
import sca.pro.common.utils.SystemUtils;
import sca.pro.gateway.feign.SystemFeignService;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author shq
* @description 身份认证过滤器
* @createDate 2022-5-25
* @updateUser
* @updateDate
* @updateRemark
*/
@Component
@EnableConfigurationProperties(JwtProperties.class)
public class AuthGatewayFilter implements GatewayFilter, Ordered {
@Resource
private JwtProperties jwtProperties;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private SystemFeignService systemFeignService;
// spring的路径匹配器
private final static AntPathMatcher antPathMatcher = new AntPathMatcher();
private static PublicKey publicKey;
private static PrivateKey privateKey;
/**
* 初始化公私钥
*
* @throws Exception
*/
@PostConstruct
public void init() throws Exception {
boolean flag = false;
String path = SystemUtils.getApplicationPath() + Contants.JWT_RSAKEY_PATH;
String pubPath = path + "/rsa.pub";
String priPath = path + "/rsa.pri";
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
} else {
File pubFile = new File(pubPath);
File priFile = new File(priPath);
if (!pubFile.exists() || !priFile.exists()) {
pubFile.delete();
priFile.delete();
} else {
flag = true;
}
}
if (!flag) {
RsaUtils.generateKey(pubPath, priPath, Contants.JWT_SECRET);
}
if (publicKey == null) {
publicKey = RsaUtils.getPublicKey(pubPath);
privateKey = RsaUtils.getPrivateKey(priPath);
}
}
/**
* 排序规则
*
* @return
*/
@Override
public int getOrder() {
return -100;
}
/**
* jwt全局过滤器
*
* @param exchange
* @param chain
* @return
*/
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 获取request和response
ServerHttpRequest request = exchange.getRequest();
ServerHttpResponse response = exchange.getResponse();
// 获取请求的url
String url = exchange.getRequest().getURI().getPath();
// 检查url放行
for (String skip : jwtProperties.getSkipAuthUrls()) {
if (antPathMatcher.match(skip, url)) {
return chain.filter(exchange);
}
}
// 检查header中jwt是否存在
MultiValueMap<String, String> headers = request.getHeaders();
if (CollectionUtils.isEmpty(headers) || !headers.containsKey(Contants.JWT_HEADER_KEY)) {
return unAuthorized(exchange);
}
// 解析jwt
String username = null;
Map<String, Object> mapInfo = null;
try {
mapInfo = JwtUtils.getInfoFromToken(headers.getFirst(Contants.JWT_HEADER_KEY), publicKey);
if (mapInfo == null || mapInfo.get("username") == null) {
return unAuthorized(exchange);
}
username = mapInfo.get("username").toString();
if (username.equals("")) {
return unAuthorized(exchange);
}
} catch (Exception e) {
return unAuthorized(exchange);
}
// 获取权限信息
AuthInfo authInfo = null;
String rKey = String.format(Contants.RKEY_SYSTEM_AUTHINFO, username);
ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
String rValue = ops.get(rKey);
if (rValue == null) {
HttpResult result = systemFeignService.getAuthInfo(username);
if (result.getCode() != HttpCode.SUCCESS || result.getData() == null) {
return unAuthorized(exchange);
} else {
authInfo = JSONUtil.toBean(result.getData().toString(), AuthInfo.class);
}
} else {
authInfo = JSONUtil.toBean(rValue, AuthInfo.class);
}
if (authInfo.getUserInfo() == null) {
return unAuthorized(exchange);
}
// 密码校验
if (!PasswordUtils.matchPassword(
mapInfo.get("password").toString(),
authInfo.getUserInfo().getPassword(),
authInfo.getUserInfo().getSalt())) {
return passwordError(exchange);
}
//判断账号是否可用
if (authInfo.getUserInfo().getUserStatus()==0){
return userNoUse(exchange);
}
String companyName = (String)mapInfo.get("companyName");
List<CompanyInfo> list = authInfo.getList();
//获取用户在当前公司的所有菜单权限
List<String> collect = list.stream().filter(g -> g.getCompanyName().equals(companyName)).flatMap((a) -> a.getRoles().stream().flatMap(b -> b.getAuthorities().stream()).distinct()).distinct().collect(Collectors.toList());
// 权限校验
if (!username.equals("system")){
if (collect.contains(url)) {
return hasNoPermission(exchange);
}
}
// 将认证信息放入header
ServerHttpRequest host = exchange.getRequest().mutate().header(Contants.JWT_MAP_KEY, JSONUtil.toJsonStr(mapInfo)).build();
ServerWebExchange build = exchange.mutate().request(host).build();
return chain.filter(build);
}
private static Mono<Void> unAuthorized(ServerWebExchange exchange) {
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.OK);
response.getHeaders().add("Content-Type", "application/json; charset=utf-8");
HttpResult result = new HttpResult().builder().code(HttpCode.UNAUTHORIZED).build();
return Mono.defer(() -> {
byte[] bytes;
try {
bytes = new ObjectMapper().writeValueAsBytes(result);
} catch (Exception e) {
throw new RuntimeException();
}
DataBuffer buffer = response.bufferFactory().wrap(bytes);
return response.writeWith(Flux.just(buffer));
});
}
private static Mono<Void> passwordError(ServerWebExchange exchange) {
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.OK);
response.getHeaders().add("Content-Type", "application/json; charset=utf-8");
HttpResult result = new HttpResult().builder().code(HttpCode.PASSWORDERROR).message("密码错误").build();
return Mono.defer(() -> {
byte[] bytes;
try {
bytes = new ObjectMapper().writeValueAsBytes(result);
} catch (Exception e) {
throw new RuntimeException();
}
DataBuffer buffer = response.bufferFactory().wrap(bytes);
return response.writeWith(Flux.just(buffer));
});
}
private static Mono<Void> userNoUse(ServerWebExchange exchange) {
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.OK);
response.getHeaders().add("Content-Type", "application/json; charset=utf-8");
HttpResult result = new HttpResult().builder().code(HttpCode.USERNOUSE).message("账号不可用,请联系管理员").build();
return Mono.defer(() -> {
byte[] bytes;
try {
bytes = new ObjectMapper().writeValueAsBytes(result);
} catch (Exception e) {
throw new RuntimeException();
}
DataBuffer buffer = response.bufferFactory().wrap(bytes);
return response.writeWith(Flux.just(buffer));
});
}
private static Mono<Void> hasNoPermission(ServerWebExchange exchange) {
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.OK);
response.getHeaders().add("Content-Type", "application/json; charset=utf-8");
HttpResult result = new HttpResult().builder().code(HttpCode.FORBIDDEN).build();
return Mono.defer(() -> {
byte[] bytes;
try {
bytes = new ObjectMapper().writeValueAsBytes(result);
} catch (Exception e) {
throw new RuntimeException();
}
DataBuffer buffer = response.bufferFactory().wrap(bytes);
return response.writeWith(Flux.just(buffer));
});
}
}
6.定义全局拦截器,再自定义一个注解,进行拦截判断,如果加了该注解,则说明该接口需要用到认证信息,则将认证信息从请求头中取出存入threadlocal中,涉及到两个类,一个是拦截器,一个是存储类,如下
package sca.pro.system.common.request;
import cn.hutool.json.JSONUtil;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import sca.pro.common.contants.Contants;
import sca.pro.common.jwt.MapInfo;
import sca.pro.common.response.HttpCode;
import sca.pro.common.response.HttpResult;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
/**
* @author shq
* @description Request拦截器
* @createDate 2022-5-27
* @updateUser
* @updateDate
* @updateRemark
*/
public class RequestContextInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (!(handler instanceof HandlerMethod)) {
return true;
}
Method method = ((HandlerMethod) handler).getMethod();
if (!method.isAnnotationPresent(AuthInfoRequired.class)) {
return true;
}
AuthInfoRequired annotation = method.getAnnotation(AuthInfoRequired.class);
if (!annotation.required()) {
return true;
}
if (initHeaderContext(request)) {
return super.preHandle(request, response, handler);
} else {
returnJson(response, JSONUtil.toJsonStr(new HttpResult().builder()
.code(HttpCode.UNAUTHORIZED).build()));
return false;
}
}
private boolean initHeaderContext(HttpServletRequest request) {
String mapInfoStr = request.getHeader(Contants.JWT_MAP_KEY);
if (mapInfoStr != null) {
try {
MapInfo mapInfo = JSONUtil.toBean(mapInfoStr, MapInfo.class);
new RequestContext.RequestContextBuild()
.mapInfo(mapInfo)
.bulid();
if (mapInfo.getUsername() == null) {
return false;
}
return true;
} catch (Exception e) {
return false;
}
} else {
return false;
}
}
private void returnJson(HttpServletResponse response, String json) throws Exception {
PrintWriter writer = null;
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=utf-8");
try {
writer = response.getWriter();
writer.print(json);
} catch (IOException e) {
} finally {
if (writer != null)
writer.close();
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
RequestContext.clean();
super.postHandle(request, response, handler, modelAndView);
}
}
package sca.pro.system.common.request;
import sca.pro.common.jwt.MapInfo;
/**
* @author shq
* @description 请求上下文声明
* @createDate 2022-5-27
* @updateUser
* @updateDate
* @updateRemark
*/
public class RequestContext {
private static final ThreadLocal<RequestContext> REQUEST_HEADER_CONTEXT_THREAD_LOCAL = new ThreadLocal<>();
private MapInfo mapInfo;
public String getUsername() {
if (mapInfo != null) {
return mapInfo.getUsername();
}
return null;
}
public String getCompanyName() {
if (mapInfo != null) {
return mapInfo.getCompanyName();
}
return null;
}
public String getlanguageName() {
if (mapInfo != null) {
return mapInfo.getLanguageName();
}
return null;
}
public static RequestContext getInstance() {
return REQUEST_HEADER_CONTEXT_THREAD_LOCAL.get();
}
public void setContext(RequestContext context) {
REQUEST_HEADER_CONTEXT_THREAD_LOCAL.set(context);
}
public static void clean() {
REQUEST_HEADER_CONTEXT_THREAD_LOCAL.remove();
}
private RequestContext(RequestContextBuild requestHeaderContextBuild) {
this.mapInfo = requestHeaderContextBuild.mapInfo;
setContext(this);
}
public static class RequestContextBuild {
private MapInfo mapInfo;
public RequestContextBuild mapInfo(MapInfo mapInfo) {
this.mapInfo = mapInfo;
return this;
}
public RequestContext bulid() {
return new RequestContext(this);
}
}
}
7.在需要使用认证信息的地方只需要加上这个AuthInfoRequired注解,即可通过RequestContext.getinstance().get对应的认证信息即可获取,到此第一种方法结束
(2)为了保证网关的业务纯净,我们一般不在网管进行鉴权,而且上述的方法也稍微有些繁琐,我们可以自定义一个注解,通过aop环绕进行统一拦截,这次设计需要在nacos中定义一个独立的白名单文件,然后还是一样先对拦截的请求进行 白名单放行,然后获取token进行解析,获取对应的用户信息进行判读密码,权限校验,与上边相同,直接上代码‘
package sca.pro.core.authentication.handler;
import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import sca.pro.common.contants.Contants;
import sca.pro.common.exception.BusinessException;
import sca.pro.common.jwt.MapInfo;
import sca.pro.common.redis.authInfo.AuthInfo;
import sca.pro.common.redis.authInfo.CompanyInfo;
import sca.pro.common.response.HttpCode;
import sca.pro.common.response.HttpResult;
import sca.pro.common.threadlocal.ThreadLocalUtils;
import sca.pro.common.utils.PasswordUtils;
import sca.pro.common.utils.SystemUtils;
import sca.pro.core.authentication.annotation.HasPermission;
import sca.pro.core.authentication.util.JwtProperties;
import sca.pro.core.authentication.util.JwtUtils;
import sca.pro.core.authentication.util.RsaUtils;
import sca.pro.core.feign.SystemCheckFeignService;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.*;
import java.util.stream.Collectors;
@Log4j2
@Aspect
// 数字越小,执行顺序越高,@Transactional的顺序为Integer.MAX_VALUE
@Order(-1)
@Component
@EnableConfigurationProperties(JwtProperties.class)
public class AuthenticationHandler {
// spring的路径匹配器
private final static AntPathMatcher antPathMatcher = new AntPathMatcher();
private static PublicKey publicKey;
private static PrivateKey privateKey;
@Resource
private JwtProperties jwtProperties;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private SystemCheckFeignService systemFeignService;
@Value("${spring.application.name}")
private String springApplicationName;
/**
* 切入点
* 1. execution 表达式主体
* 2. * 任意类型返回值
* 3. com.company.web.controller 切入包
* 4. .. 当前包及子包
* 5. * 所有类
* 6. .*(..) 所有方法与任何参数
*/
@Pointcut("execution(* sca.pro.*.controller..*.*(..)))")
public void cut() {
}
/**
* 本执行在事务外层,在GlobalExceptionHandler内层
*
* @param joinPoint
* @throws Throwable
*/
@Around("cut()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
long startTime = System.currentTimeMillis();
ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = sra.getRequest();
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
log.info("Request begin");
log.info("ModuleName: {}", springApplicationName);
log.info("RequestMethod: {}", request.getMethod());
log.info("RequestURI: {}", request.getRequestURI());
log.info("RemoteAddr: {}", request.getRemoteAddr());
log.info("MethodName: {}", methodSignature.getDeclaringTypeName() + "." + methodSignature.getName());
// todo 入参待处理
// Object[] args = joinPoint.getArgs();
// 用户身份认证
// 网关强制过滤掉了GlobalContants.HEADER_LOGIN_INFO_BASE64_KEY,在内部进行构建
boolean isLoginInfoRequired = methodSignature.getMethod().isAnnotationPresent(HasPermission.class);
try {
if (isLoginInfoRequired) {
String loginInfoStr = sra.getRequest().getHeader(Contants.HEADER_LOGIN_INFO_BASE64_KEY);
if (loginInfoStr != null) {
// 将请求头信息加入本地变量,用于跨服务调用 将请求头信息进行解析,用于业务处理
ThreadLocalUtils.set(Contants.HEADER_LOGIN_INFO_BASE64_KEY, loginInfoStr);
MapInfo mapInfo=JSONUtil.toBean(JSONUtil.parseObj(loginInfoStr), MapInfo.class);
ThreadLocalUtils.set(Contants.LOCAL_LOGIN_INFO_OBJECT_KEY, mapInfo);
} else {
// 获取request和response
// 获取请求的url
String url =request.getRequestURI() ;
// 检查url白名单放行
for (String skip : jwtProperties.getSkipAuthUrls()) {
if (antPathMatcher.match(skip, url)) {
Object object = joinPoint.proceed(joinPoint.getArgs());
// todo 出参待处理
return object;
}
}
Map<String, Object> mapInfo = null;
AuthInfo authInfo = null;
// 检查header中jwt是否存在
String header = request.getHeader(Contants.JWT_HEADER_KEY);
if (StringUtils.isEmpty(header)) {
throw new BusinessException(HttpCode.UNAUTHORIZED, "未授权");
}
// 解析jwt
String username = null;
try {
mapInfo = JwtUtils.getInfoFromToken(URLDecoderString(header), publicKey);
if (mapInfo == null || mapInfo.get("username") == null) {
throw new BusinessException(HttpCode.UNAUTHORIZED, "未授权");
}
username = mapInfo.get("username").toString();
if (username.equals("")) {
throw new BusinessException(HttpCode.UNAUTHORIZED, "未授权");
}
//判断token是否是最新的
String token = systemFeignService.getToken(username);
if (token!=null){
if (!token.equals(header)){
throw new BusinessException(7777, "账号已在别处登录");
}
}
} catch (Exception e) {
throw new BusinessException(HttpCode.UNAUTHORIZED, "未授权");
}
// 获取权限信息
String rKey = String.format(Contants.RKEY_SYSTEM_AUTHINFO, username);
rKey = StringUtils.join(rKey, ":", username);
ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
String rValue = ops.get(rKey);
if (rValue == null) {
HttpResult result = systemFeignService.getAuthInfo(username, mapInfo.get("companyName").toString());
if (result.getCode() != HttpCode.SUCCESS || result.getData() == null) {
throw new BusinessException(HttpCode.UNAUTHORIZED, "未授权");
} else {
authInfo = JSONUtil.toBean(result.getData().toString(), AuthInfo.class);
}
} else {
authInfo = JSONUtil.toBean(rValue, AuthInfo.class);
}
if (authInfo.getUserInfo() == null) {
throw new BusinessException(HttpCode.UNAUTHORIZED, "未授权");
}
// 密码校验
if (!PasswordUtils.matchPassword(
mapInfo.get("password").toString(),
authInfo.getUserInfo().getPassword(),
authInfo.getUserInfo().getSalt())) {
throw new BusinessException(HttpCode.PASSWORDERROR, "密码错误");
}
//判断账号是否可用
if (authInfo.getUserInfo().getUserStatus() == 0) {
throw new BusinessException(HttpCode.USERNOUSE, "账号不可用请联系管理员");
}
String companyName = (String) mapInfo.get("companyName");
List<CompanyInfo> list = authInfo.getList();
//获取用户在当前公司的所有菜单权限
List<String> collect = list.stream().filter(g -> g.getCompanyName().equals(companyName)).flatMap((a) -> a.getRoles().stream().flatMap(b -> b.getAuthorities().stream()).distinct()).distinct().collect(Collectors.toList());
// 权限校验
if (!username.equals("system")) {
if (collect.contains(url)) {
throw new BusinessException(HttpCode.FORBIDDEN, "无权限");
}
}
// 将请求头信息加入本地变量,用于跨服务调用 将请求头信息进行解析,用于业务处理
ThreadLocalUtils.set(Contants.HEADER_LOGIN_INFO_BASE64_KEY,JSONUtil.toJsonStr( Convert.convert(MapInfo.class,mapInfo)));
MapInfo loginInfo =Convert.convert(MapInfo.class,mapInfo);
ThreadLocalUtils.set(Contants.LOCAL_LOGIN_INFO_OBJECT_KEY, loginInfo);
}
}
Object object = joinPoint.proceed(joinPoint.getArgs());
// todo 出参待处理
return object;
} catch (Throwable e) {
throw e;
} finally {
log.info("Cost time: {}ms", System.currentTimeMillis() - startTime);
ThreadLocalUtils.clear();
}
}
public static String URLDecoderString(String str) {
String result = "";
if (null == str) {
return "";
}
try {
result = java.net.URLDecoder.decode(str, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
/**
* 初始化公私钥
*
* @throws Exception
*/
@PostConstruct
public void init() throws Exception {
boolean flag = false;
String path = SystemUtils.getApplicationPath() + Contants.JWT_RSAKEY_PATH;
String pubPath = path + "/rsa.pub";
String priPath = path + "/rsa.pri";
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
} else {
File pubFile = new File(pubPath);
File priFile = new File(priPath);
if (!pubFile.exists() || !priFile.exists()) {
pubFile.delete();
priFile.delete();
} else {
flag = true;
}
}
if (!flag) {
RsaUtils.generateKey(pubPath, priPath, Contants.JWT_SECRET);
}
if (publicKey == null) {
publicKey = RsaUtils.getPublicKey(pubPath);
privateKey = RsaUtils.getPrivateKey(priPath);
}
}
}