优化登录接口,优化token,新增登录日志,处理redis连接问题

master
邱飞云 4 years ago
parent b091feba29
commit 7f743e7dfb
  1. 35
      dq-financial-hrms-auth/pom.xml
  2. 9
      dq-financial-hrms-auth/src/main/java/com/daqing/financial/hrauth/dao/LoginLogMapper.java
  3. 9
      dq-financial-hrms-auth/src/main/java/com/daqing/financial/hrauth/dao/TokenMapper.java
  4. 7
      dq-financial-hrms-auth/src/main/java/com/daqing/financial/hrauth/service/LoginLogService.java
  5. 7
      dq-financial-hrms-auth/src/main/java/com/daqing/financial/hrauth/service/TokenService.java
  6. 11
      dq-financial-hrms-auth/src/main/java/com/daqing/financial/hrauth/service/impl/LoginLogServiceImpl.java
  7. 11
      dq-financial-hrms-auth/src/main/java/com/daqing/financial/hrauth/service/impl/TokenServiceImpl.java
  8. 57
      dq-financial-hrms-auth/src/main/java/com/daqing/financial/hrauth/service/impl/UserLoginServiceImpl.java
  9. 71
      dq-financial-hrms-auth/src/main/java/com/daqing/financial/hrauth/util/JwtUtil.java
  10. 10
      dq-financial-hrms-auth/src/main/resources/bootstrap.properties
  11. 94
      dq-financial-hrms/src/main/java/com/daqing/financial/hrms/config/ResourceServerConfig.java
  12. 49
      dq-framework-common/pom.xml
  13. 2
      dq-framework-common/src/main/java/com/daqing/framework/SpringContextHolder.java
  14. 97
      dq-framework-common/src/main/java/com/daqing/framework/util/JwtUtils.java
  15. 11
      dq-framework-common/src/main/java/com/daqing/framework/util/RedisUtil.java
  16. 28
      dq-framework-model/src/main/java/com/daqing/framework/domain/hrms/LoginLog.java
  17. 18
      dq-framework-model/src/main/java/com/daqing/framework/domain/hrms/Token.java
  18. 29
      dq-framework-utils/pom.xml
  19. 17
      dq-govern-gateway/pom.xml
  20. 19
      dq-govern-gateway/src/main/java/com/daqing/financial/gateway/config/ApiGlobalFilter.java

@ -25,43 +25,32 @@
<artifactId>dq-framework-common</artifactId> <artifactId>dq-framework-common</artifactId>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
</dependency>--> </dependency>-->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency>
<dependency> <dependency>
<groupId>com.daqing.framework</groupId> <groupId>com.daqing.framework</groupId>
<artifactId>dq-framework-model</artifactId> <artifactId>dq-framework-model</artifactId>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--<dependency>
<groupId>com.daqing.financial</groupId>
<artifactId>dq-govern-gateway</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>-->
<!--<dependency> <!--<dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>--> </dependency>-->
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId> <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency> </dependency>
<!-- <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>-->
<!--<dependency> <!--<dependency>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>

@ -0,0 +1,9 @@
package com.daqing.financial.hrauth.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.daqing.framework.domain.hrms.LoginLog;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface LoginLogMapper extends BaseMapper<LoginLog> {
}

@ -0,0 +1,9 @@
package com.daqing.financial.hrauth.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.daqing.framework.domain.hrms.Token;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface TokenMapper extends BaseMapper<Token> {
}

@ -0,0 +1,7 @@
package com.daqing.financial.hrauth.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.daqing.framework.domain.hrms.LoginLog;
public interface LoginLogService extends IService<LoginLog> {
}

@ -0,0 +1,7 @@
package com.daqing.financial.hrauth.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.daqing.framework.domain.hrms.Token;
public interface TokenService extends IService<Token> {
}

@ -0,0 +1,11 @@
package com.daqing.financial.hrauth.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.daqing.financial.hrauth.dao.LoginLogMapper;
import com.daqing.financial.hrauth.service.LoginLogService;
import com.daqing.framework.domain.hrms.LoginLog;
import org.springframework.stereotype.Service;
@Service
public class LoginLogServiceImpl extends ServiceImpl<LoginLogMapper, LoginLog> implements LoginLogService {
}

@ -0,0 +1,11 @@
package com.daqing.financial.hrauth.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.daqing.financial.hrauth.dao.TokenMapper;
import com.daqing.financial.hrauth.service.TokenService;
import com.daqing.framework.domain.hrms.Token;
import org.springframework.stereotype.Service;
@Service
public class TokenServiceImpl extends ServiceImpl<TokenMapper, Token> implements TokenService {
}

@ -1,9 +1,13 @@
package com.daqing.financial.hrauth.service.impl; package com.daqing.financial.hrauth.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.daqing.financial.hrauth.dao.UserLoginDao; import com.daqing.financial.hrauth.dao.UserLoginDao;
import com.daqing.financial.hrauth.service.LoginLogService;
import com.daqing.financial.hrauth.service.TokenService;
import com.daqing.financial.hrauth.service.UserLoginService; import com.daqing.financial.hrauth.service.UserLoginService;
import com.daqing.financial.hrauth.util.JwtUtil; import com.daqing.framework.domain.hrms.LoginLog;
import com.daqing.framework.domain.hrms.Token;
import com.daqing.framework.domain.hrms.UserEntity; import com.daqing.framework.domain.hrms.UserEntity;
import com.daqing.framework.domain.hrms.request.LoginRequest; import com.daqing.framework.domain.hrms.request.LoginRequest;
import com.daqing.framework.domain.hrms.request.UserLoginRequest; import com.daqing.framework.domain.hrms.request.UserLoginRequest;
@ -12,11 +16,15 @@ import com.daqing.framework.domain.hrms.response.LoginResponse;
import com.daqing.framework.exception.ExceptionCast; import com.daqing.framework.exception.ExceptionCast;
import com.daqing.framework.model.response.CommonCode; import com.daqing.framework.model.response.CommonCode;
import com.daqing.framework.model.response.ResponseResult; import com.daqing.framework.model.response.ResponseResult;
import com.daqing.framework.util.JwtUtils;
import com.daqing.framework.util.Md5Util; import com.daqing.framework.util.Md5Util;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.util.Date;
/** /**
* @auther River * @auther River
@ -28,6 +36,12 @@ public class UserLoginServiceImpl extends ServiceImpl<UserLoginDao, UserEntity>
@Resource @Resource
private UserLoginDao userLoginDao; private UserLoginDao userLoginDao;
@Autowired
private TokenService tokenService;
@Autowired
private LoginLogService loginLogService;
/* @Autowired /* @Autowired
private OdcProperties properties;*/ private OdcProperties properties;*/
@ -102,6 +116,7 @@ public class UserLoginServiceImpl extends ServiceImpl<UserLoginDao, UserEntity>
return i > 0; return i > 0;
} }
@Transactional
public ResponseResult login(LoginRequest loginRequest) { public ResponseResult login(LoginRequest loginRequest) {
//判断用户登录方式 //判断用户登录方式
UserEntity userEntity = baseMapper.login(loginRequest); UserEntity userEntity = baseMapper.login(loginRequest);
@ -115,23 +130,49 @@ public class UserLoginServiceImpl extends ServiceImpl<UserLoginDao, UserEntity>
return ResponseResult.FAIL(CommonCode.PASSWORD_IS_ERROR.code(), CommonCode.PASSWORD_IS_ERROR.message()); return ResponseResult.FAIL(CommonCode.PASSWORD_IS_ERROR.code(), CommonCode.PASSWORD_IS_ERROR.message());
} }
}else {//微信登录 }else {//微信登录
} }
//登录成功,token生成 //登录成功,token生成
long times = 84600; long times = 84600;
if(loginRequest.getTenDayEffective() == 1){ if(loginRequest.getTenDayEffective() == 1){
times = 846000; times = 846000;
} }
String token = JwtUtil.createJwtToken(userEntity.getId(), times); String token = JwtUtils.createJWT(userEntity.getId(),"token", times);
if (true) { Token userToken = tokenService.getOne(new QueryWrapper<Token>().eq("user_id", userEntity.getId()));
JwtUtil.removeTokenByUserId(userEntity.getId()); if(userToken != null){
//删除redis里面的token
JwtUtils.removeTokenByToken(userToken.getToken());
//数据库重置token
userToken.setToken(token);
userToken.setCreateTime(new Date());
tokenService.updateById(userToken);
}else {
userToken = new Token();
userToken.setUserId(userEntity.getId());
userToken.setToken(token);
userToken.setCreateTime(new Date());
tokenService.save(userToken);
}
//设置最新的token到redis
JwtUtils.putTokenToRedis(userEntity.getId(), token, times);
//新增登录日志
LoginLog loginLog = loginLogService.getOne(new QueryWrapper<LoginLog>().eq("user_id", userEntity.getId()));
if(loginLog == null){
loginLog = new LoginLog();
loginLog.setUserId(userEntity.getId());
loginLog.setLoginNum(1);
loginLog.setCreateTime(new Date());
loginLog.setNewestTime(new Date());
loginLogService.save(loginLog);
}else {
loginLog.setLoginNum(loginLog.getLoginNum() + 1);
loginLog.setNewestTime(new Date());
loginLogService.updateById(loginLog);
} }
JwtUtil.putTokenToRedis(userEntity.getId(), token, times);
//返回用户信息 //返回用户信息
LoginResponse loginResponse = new LoginResponse(); LoginResponse loginResponse = new LoginResponse();
loginResponse.setAccount(userEntity.getAccount()); loginResponse.setAccount(userEntity.getAccount());
loginResponse.setToken(token); loginResponse.setToken(token);

@ -1,71 +0,0 @@
package com.daqing.financial.hrauth.util;
import com.daqing.framework.util.Md5Util;
import java.util.Set;
/**
* @author zcw
* @version 1.0
* @date 2019/11/23 11:06
* @description jwt工具类
*/
public class JwtUtil {
//private final static Algorithm algorithm = SpringContextHolder.getBean("algorithm", Algorithm.class);
//private final static OdcProperties properties = SpringContextHolder.getBean("odcProperties", OdcProperties.class);
/**
* 创建token
*
* @param userId;
* @param timeout; 单位是秒
*/
public static String createJwtToken(Long userId, long timeout) {
String token = Md5Util.md5("dq"+userId+timeout+System.currentTimeMillis());
RedisUtil.setEx("dq:token:"+token, String.valueOf(userId), timeout);
return token;
/*return JWT.create()
.withClaim("member", userId)
.withExpiresAt(new Date(System.currentTimeMillis() + timeout * 1000))
.sign(algorithm);*/
}
/**
* token正确且有效则返回userId
*/
/* public static Long verifyToken(String token) {
try {
String noBearerToken = token.replaceFirst("Bearer ", "");
Long userId = JWT.require(algorithm)
.build()
.verify(noBearerToken)
.getClaim("member")
.asLong();
if (RedisUtil.get(getRedisKey(userId, noBearerToken)) != null) {
return userId;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}*/
public static String getRedisKey(Long userId, String token) {
return String.format("dq:token:"+token, token, String.valueOf(userId));
}
public static void putTokenToRedis(Long userId, String token, long times) {
RedisUtil.setEx(getRedisKey(userId, token), "nothing", times);
}
public static void removeTokenByUserId(Long userId) {
Set<String> tokenSet = RedisUtil.keys(getRedisKey(userId, "*"));
for (String key : tokenSet) {
RedisUtil.del(key);
}
}
}

@ -17,3 +17,13 @@ spring.cloud.nacos.config.ext-config[1].refresh=true
spring.cloud.nacos.config.ext-config[2].data-id=other.yml spring.cloud.nacos.config.ext-config[2].data-id=other.yml
spring.cloud.nacos.config.ext-config[2].group=dev spring.cloud.nacos.config.ext-config[2].group=dev
spring.cloud.nacos.config.ext-config[2].refresh=true spring.cloud.nacos.config.ext-config[2].refresh=true
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=123456
spring.redis.database=0
spring.redis.timeout=30000
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-wait=-1
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.min-idle=0

@ -1,47 +1,47 @@
package com.daqing.financial.hrms.config; //package com.daqing.financial.hrms.config;
//
import org.springframework.beans.factory.annotation.Value; //import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean; //import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; //import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; //import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; //import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; //import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; //import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices; //import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
//
@Configuration //@Configuration
@EnableResourceServer //@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true) //@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter { //public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
//
@Value("${security.oauth2.client.client-id}") // @Value("${security.oauth2.client.client-id}")
private String clientId; // private String clientId;
//
@Value("${security.oauth2.client.client-secret}") // @Value("${security.oauth2.client.client-secret}")
private String secret; // private String secret;
//
@Value("${security.oauth2.authorization.check-token-access}") // @Value("${security.oauth2.authorization.check-token-access}")
private String checkTokenEndpointUrl; // private String checkTokenEndpointUrl;
//
/* @Autowired // /* @Autowired
private RedisConnectionFactory redisConnectionFactory;*/ // private RedisConnectionFactory redisConnectionFactory;*/
//
/* @Bean ///* @Bean
public TokenStore redisTokenStore (){ // public TokenStore redisTokenStore (){
return new RedisTokenStore(redisConnectionFactory); // return new RedisTokenStore(redisConnectionFactory);
}*/ // }*/
//
@Bean // @Bean
public RemoteTokenServices tokenService() { // public RemoteTokenServices tokenService() {
RemoteTokenServices tokenService = new RemoteTokenServices(); // RemoteTokenServices tokenService = new RemoteTokenServices();
tokenService.setClientId(clientId); // tokenService.setClientId(clientId);
tokenService.setClientSecret(secret); // tokenService.setClientSecret(secret);
tokenService.setCheckTokenEndpointUrl(checkTokenEndpointUrl); // tokenService.setCheckTokenEndpointUrl(checkTokenEndpointUrl);
return tokenService; // return tokenService;
} // }
//
@Override // @Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception { // public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenServices(tokenService()); // resources.tokenServices(tokenService());
} // }
} //}

@ -19,18 +19,7 @@
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
<!--<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>7</source>
<target>7</target>
</configuration>
</plugin>
</plugins>
</build>-->
<dependencies> <dependencies>
<!--导入mysql驱动--> <!--导入mysql驱动-->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
@ -51,17 +40,24 @@
<artifactId>mybatis-plus-generator</artifactId> <artifactId>mybatis-plus-generator</artifactId>
<version>3.0.7.1</version> <version>3.0.7.1</version>
</dependency> </dependency>
<!--<dependency> <!--LOMBOK-->
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1</version>
</dependency>-->
<dependency> <dependency>
<groupId>org.projectlombok</groupId> <groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId> <artifactId>lombok</artifactId>
<version>1.18.12</version> <version>1.18.12</version>
</dependency> </dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>
<!--swagger--> <!--swagger-->
<dependency> <dependency>
<groupId>io.springfox</groupId> <groupId>io.springfox</groupId>
@ -75,16 +71,14 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>com.auth0</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>java-jwt</artifactId>
<version>2.1.8.RELEASE</version> <version>3.2.0</version>
<!--<exclusions> </dependency>
&lt;!&ndash;排除jackson&ndash;&gt; <dependency>
<exclusion> <groupId>io.jsonwebtoken</groupId>
<groupId>com.fasterxml.jackson.core</groupId> <artifactId>jjwt</artifactId>
<artifactId>jackson-databind</artifactId> <version>0.7.0</version>
</exclusion>
</exclusions>-->
</dependency> </dependency>
<!--<scope>provided</scope> 设置成目标环境已存在,打包的时候不会带上这个jar--> <!--<scope>provided</scope> 设置成目标环境已存在,打包的时候不会带上这个jar-->
<dependency> <dependency>
@ -99,6 +93,7 @@
<version>5.2.8.RELEASE</version> <version>5.2.8.RELEASE</version>
</dependency> </dependency>
<!--google工具类-->
<dependency> <dependency>
<groupId>com.google.guava</groupId> <groupId>com.google.guava</groupId>
<artifactId>guava</artifactId> <artifactId>guava</artifactId>

@ -1,4 +1,4 @@
package com.daqing.financial.hrauth; package com.daqing.framework;
import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;

@ -0,0 +1,97 @@
package com.daqing.framework.util;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.bouncycastle.util.encoders.Base64;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SignatureException;
import java.util.Date;
public class JwtUtils {
/**
* 签发JWT
*
* @param id
* @param subject 可以是JSON数据 尽可能少
* @param ttlMillis
* @return String
*
*/
public static String createJWT(Long id, String subject, long ttlMillis) {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
SecretKey secretKey = generalKey();
JwtBuilder builder = Jwts.builder().setId(String.valueOf(id)).setSubject(subject) // 主题
.setIssuer("user") // 签发者
.setIssuedAt(now) // 签发时间
.signWith(signatureAlgorithm, secretKey); // 签名算法以及密匙
if (ttlMillis >= 0) {
long expMillis = nowMillis + ttlMillis;
Date expDate = new Date(expMillis);
builder.setExpiration(expDate); // 过期时间
}
return builder.compact();
}
public static void main(String[] args) {
//System.out.printf(createJWT("1","111", 10000000));
boolean isTrue = validateJWT("eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxIiwic3ViIjoiMTExIiwiaXNzIjoidXNlciIsImlhdCI6MTYwMTM0MzYyNywiZXhwIjoxNjAxMzUzNjI3fQ.q5Ssg2LM1OzzgvVWqLhgP_Hko0-pfeNO5bvpUE5KQ-s");
System.out.println(isTrue);
}
/**
* 验证JWT
*
* @param jwtStr
* @return
*/
public static Boolean validateJWT(String jwtStr) {
//boolean isValidate = false;
Claims claims = null;
try {
claims = parseJWT(jwtStr);
return true;
} catch (ExpiredJwtException e) {
return false;
} catch (SignatureException e) {
return false;
} catch (Exception e) {
return false;
}
//return checkResult;
}
public static SecretKey generalKey() {
byte[] encodedKey = Base64.decode("JWTDQ123456");
SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
return key;
}
/**
*
* 解析JWT字符串
*
* @param jwt
* @return
* @throws Exception
*/
public static Claims parseJWT(String jwt) throws Exception {
SecretKey secretKey = generalKey();
return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody();
}
public static void putTokenToRedis(Long userId, String token, long times) {
RedisUtil.setEx("dq:token:"+token, String.valueOf(userId), times);
}
public static void removeTokenByToken(String token) {
RedisUtil.del("dq:token:"+token);
}
}

@ -1,7 +1,7 @@
package com.daqing.financial.hrauth.util; package com.daqing.framework.util;
import com.daqing.financial.hrauth.SpringContextHolder; import com.daqing.framework.SpringContextHolder;
import org.springframework.data.redis.core.HashOperations; import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations; import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate;
@ -19,6 +19,13 @@ public class RedisUtil {
private final static StringRedisTemplate stringRedisTemplate = SpringContextHolder.getBean("stringRedisTemplate"); private final static StringRedisTemplate stringRedisTemplate = SpringContextHolder.getBean("stringRedisTemplate");
/*static private RedisTemplate stringRedisTemplate;
static private RedisTemplate getRedisTemplate() {
if (stringRedisTemplate == null) {
stringRedisTemplate = SpringContextHolder.getBean("redisTemplate");
}
return stringRedisTemplate;
}*/
/** /**
* 匹配key * 匹配key
*/ */

@ -0,0 +1,28 @@
package com.daqing.framework.domain.hrms;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.util.Date;
@Data
@TableName("hrms_login_log")
public class LoginLog {
@TableId(type = IdType.AUTO)
private int id;
//用户id
private Long userId;
//登录次数
private int loginNum;
//创建时间
private Date createTime;
//最新登录时间
private Date newestTime;
}

@ -0,0 +1,18 @@
package com.daqing.framework.domain.hrms;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.util.Date;
@Data
@TableName("hrms_token")
public class Token {
@TableId(type = IdType.INPUT)
private Long userId;
private String token;
private Date createTime;
}

@ -25,18 +25,6 @@
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
<!--<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>7</source>
<target>7</target>
</configuration>
</plugin>
</plugins>
</build>-->
<dependencies> <dependencies>
<dependency> <dependency>
@ -44,6 +32,11 @@
<artifactId>dq-framework-common</artifactId> <artifactId>dq-framework-common</artifactId>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.1.8.RELEASE</version>
</dependency>
<dependency> <dependency>
<groupId>com.aliyun.oss</groupId> <groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId> <artifactId>aliyun-sdk-oss</artifactId>
@ -66,17 +59,5 @@
<version>5.1.9.RELEASE</version> <version>5.1.9.RELEASE</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<!-- <dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-core</artifactId>
<version>3.0.7.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
<version>3.0.7.1</version>
<scope>compile</scope>
</dependency>-->
</dependencies> </dependencies>
</project> </project>

@ -21,11 +21,16 @@
<dependencies> <dependencies>
<dependency>
<groupId>com.daqing.framework</groupId>
<artifactId>dq-framework-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId> <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency> </dependency>
<dependency> <!--<dependency>
<groupId>commons-lang</groupId> <groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId> <artifactId>commons-lang</artifactId>
<version>2.6</version> <version>2.6</version>
@ -34,9 +39,9 @@
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId> <artifactId>commons-lang3</artifactId>
<version>3.8.1</version> <version>3.8.1</version>
</dependency> </dependency>-->
<dependency> <!-- <dependency>
<groupId>com.alibaba</groupId> <groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId> <artifactId>fastjson</artifactId>
<version>1.2.70</version> <version>1.2.70</version>
@ -47,11 +52,11 @@
<artifactId>lombok</artifactId> <artifactId>lombok</artifactId>
<version>1.18.12</version> <version>1.18.12</version>
</dependency> </dependency>
-->
<dependency> <!-- <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId> <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency> </dependency>-->
</dependencies> </dependencies>

@ -1,7 +1,8 @@
package com.daqing.financial.gateway.config; package com.daqing.financial.gateway.config;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.daqing.financial.gateway.util.RedisUtil; import com.daqing.framework.util.JwtUtils;
import com.daqing.framework.util.RedisUtil;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GatewayFilterChain;
@ -57,9 +58,9 @@ public class ApiGlobalFilter implements GlobalFilter, Ordered {
//有数据 //有数据
}else { }else {
//校验token //校验token
//Long userId = verifyJWT(token); boolean isVerify = verifyJWT(token);
String userId = RedisUtil.get("dq:token:"+token); //String userId = RedisUtil.get("dq:token:"+token);
if (userId == null || "".equals(userId)){ if (! isVerify){
JSONObject message = new JSONObject(); JSONObject message = new JSONObject();
message.put("message", "登录已失效,请重新登录"); message.put("message", "登录已失效,请重新登录");
message.put("code", "401"); message.put("code", "401");
@ -70,7 +71,7 @@ public class ApiGlobalFilter implements GlobalFilter, Ordered {
return response.writeWith(Mono.just(buffer)); return response.writeWith(Mono.just(buffer));
} }
//将现在的request,添加当前身份 //将现在的request,添加当前身份
ServerHttpRequest mutableReq = exchange.getRequest().mutate().header("Authorization-UserId", userId).build(); ServerHttpRequest mutableReq = exchange.getRequest().mutate().header("Authorization", token).build();
ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build(); ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build();
return chain.filter(mutableExchange); return chain.filter(mutableExchange);
} }
@ -83,9 +84,13 @@ public class ApiGlobalFilter implements GlobalFilter, Ordered {
* @param token * @param token
* @return userPhone * @return userPhone
*/ */
private Long verifyJWT(String token){ private Boolean verifyJWT(String token){
String id = RedisUtil.get("dq:token:"+token); String id = RedisUtil.get("dq:token:"+token);
return Long.parseLong(id); if(id == null || "".equals(id)){
return false;
}
return JwtUtils.validateJWT(token);
//return Long.parseLong(id);
} }
@Override @Override

Loading…
Cancel
Save