<fix> 解决token失效时间相关问题

This commit is contained in:
lhc
2022-07-13 16:54:42 +08:00
parent f022d3e56a
commit 3b9d134d3e
8 changed files with 109 additions and 82 deletions

View File

@@ -50,7 +50,7 @@ public class CustomRealm extends AuthorizingRealm {
String accessToken = (String) token.getPrincipal();
String userId;
if (frameConfig.getCas()) {
Map<Object, Object> hashMap = (Map<Object, Object>) redisUtil.hget("session", accessToken);
Map<Object, Object> hashMap = (Map<Object, Object>) redisUtil.get("session:"+accessToken);
Long expireTime = (Long) hashMap.get("expireTime");
expireTime = expireTime * 1000;
AssertionImpl assertion = (AssertionImpl) hashMap.get("_const_cas_assertion_");
@@ -61,21 +61,19 @@ public class CustomRealm extends AuthorizingRealm {
}
return new SimpleAuthenticationInfo(attributePrincipal.getAttributes(), accessToken, this.getName());
} else if (frameConfig.getIsRedisLogin()) {
Map<Object, Object> hashMap = (Map<Object, Object>) redisUtil.hget("tokenSession", accessToken);
userId = (String) hashMap.get("userId");
userId= (String) redisUtil.hget("tokenSession:"+accessToken,"userId");
if (userId == null) {
throw new IncorrectCredentialsException("token失效请重新登录");
}
if (frameConfig.getSingleClientLogin()) {
String tokenStr = (String) redisUtil.hget("session", String.valueOf(userId));
String tokenStr = (String) redisUtil.get("session:"+userId);
if (tokenStr == null || !tokenStr.equals(accessToken)) {
redisUtil.del(accessToken);
throw new IncorrectCredentialsException("token失效请重新登录");
}
}
Date expireTime = (Date) hashMap.get("expireTime");
System.out.println(expireTime);
if (expireTime.getTime() < System.currentTimeMillis()) {
long time = Long.parseLong((String) redisUtil.hget("tokenSession:" + accessToken, "expireTime"));
if (time < System.currentTimeMillis()) {
redisUtil.del(accessToken);
throw new IncorrectCredentialsException("token失效请重新登录");
}

View File

@@ -55,12 +55,16 @@ public class ShiroServiceImpl implements ShiroService {
Date now = new Date();
// 是否使用redis存入token
if (isRedisLogin) {
boolean flag = redisUtil.hset("session", String.valueOf(userId), token, EXPIRE / 1000);
boolean flag = redisUtil.set("session:"+userId, token, EXPIRE / 1000);
if (flag) {
Map<String, Object> map = new HashMap<>(2);
map.put("userId", userId);
map.put("expireTime", expireTime);
flag = redisUtil.hset("tokenSession",token, map, EXPIRE / 1000);
flag = redisUtil.hset("tokenSession:" + token, "userId", userId, EXPIRE / 1000);
if (!flag) {
throw new ServiceException("登陆失败");
}
flag = redisUtil.hset("tokenSession:" + token, "expireTime", String.valueOf(expireTime.getTime()), EXPIRE / 1000);
if (!flag) {
throw new ServiceException("登陆失败");
}
@@ -97,10 +101,10 @@ public class ShiroServiceImpl implements ShiroService {
@Override
public ResultVO logout(String accessToken) {
if (isRedisLogin) {
Map<Object, Object> map = (Map<Object, Object>) redisUtil.hget("tokenSession",accessToken);
Map<Object, Object> map = (Map<Object, Object>) redisUtil.get("tokenSession:"+accessToken);
String userId = (String) map.get("userId");
redisUtil.hdel("tokenSession",accessToken);
redisUtil.hdel("session", userId);
redisUtil.del("tokenSession:"+accessToken);
redisUtil.del("session:"+userId);
return ResultVO.getSuccess();
} else {
//生成一个token

View File

@@ -48,7 +48,7 @@ public class CasController {
@GetMapping("userinfo")
@ResponseBody
public ResultVO<Object> getUserInfo(String token) {
return ResultVO.getSuccess(redisUtil.hget("session", token));
return ResultVO.getSuccess(redisUtil.get("session:"+token));
}
@GetMapping("/cas/logout")
@@ -56,7 +56,7 @@ public class CasController {
public ResultVO<String> logout(HttpServletResponse response, @CookieValue("X-Access-Token") String token) {
Cookie cookie = new Cookie("X-Access-Token", null);
cookie.setMaxAge(0);
redisUtil.hdel("session", token);
redisUtil.del("session:"+ token);
return ResultVO.getSuccess("http://192.168.1.131:8080/cas/logout");
}

View File

@@ -1,11 +1,12 @@
package com.hcframe.gateway.config;
import com.hcframe.gateway_cas_stater.data.DataStorage;
import com.hcframe.redis.RedisUtil;
import org.springframework.data.redis.core.RedisTemplate;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* @author lhc
@@ -18,7 +19,7 @@ public class MyDataStorage implements DataStorage {
private Long expireTime;
@Resource
private RedisUtil redisUtil;
private RedisTemplate redisTemplate;
public MyDataStorage(Long expireTime) {
if (expireTime==null){
@@ -29,7 +30,7 @@ public class MyDataStorage implements DataStorage {
@Override
public Object getValue(String userKey, String key) {
Map<String,Object> map = (Map<String, Object>) redisUtil.hget(SESSION, userKey);
Map<String,Object> map = (Map<String, Object>) redisTemplate.opsForHash().get(SESSION, userKey);
if (map == null) {
return null;
}
@@ -41,15 +42,15 @@ public class MyDataStorage implements DataStorage {
@Override
public void setValue(String userKey, String key, Object attr) {
Map<String,Object> map = (Map<String, Object>) redisUtil.hget(SESSION, userKey);
Map<String,Object> map = (Map<String, Object>) redisTemplate.opsForHash().get(SESSION, userKey);
if (map != null) {
map.put(key, attr);
redisUtil.hset("session", userKey, map, expireTime);
redisTemplate.opsForValue().set("session:"+userKey, map, expireTime, TimeUnit.SECONDS);
} else {
map = new HashMap<>(2);
map.put(key, attr);
map.put(EXPIRE_TIME, expireTime);
redisUtil.hset("session", userKey, map, expireTime);
redisTemplate.opsForValue().set("session:"+userKey, map, expireTime, TimeUnit.SECONDS);
}
}
}

View File

@@ -20,5 +20,14 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
</dependencies>
</project>

View File

@@ -1,10 +1,16 @@
package com.hcframe.redis;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
@@ -23,14 +29,21 @@ public class RedisConfig {
* @return
*/
@Bean("hcframeRedisTemplate")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
// 使用Jackson2JsonRedisSerialize 替换默认序列化(默认采用的是JDK序列化)
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance ,
ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
jackson2JsonRedisSerializer.setObjectMapper(om);
redisTemplate.setKeySerializer(redisSerializer);
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setHashKeySerializer(jackson2JsonRedisSerializer);
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
return redisTemplate;
}
}

View File

@@ -2,8 +2,7 @@ package com.hcframe.redis;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
@@ -23,10 +22,13 @@ public final class RedisUtil {
private final static Logger logger = LoggerFactory.getLogger(RedisUtil.class);
@Resource
@Qualifier("hcframeRedisTemplate")
private RedisTemplate<String, Object> redisTemplate;
// @Resource
// @Qualifier("hcframeRedisTemplate")
// private RedisTemplate<String, Object> stringRedisTemplate;
@Resource
private StringRedisTemplate stringRedisTemplate;
/**
* 指定缓存失效时间
*
@@ -37,7 +39,7 @@ public final class RedisUtil {
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
@@ -53,7 +55,7 @@ public final class RedisUtil {
* @return 时间(秒) 返回0代表为永久有效
*/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
return stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
@@ -64,7 +66,7 @@ public final class RedisUtil {
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
return stringRedisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
@@ -80,9 +82,9 @@ public final class RedisUtil {
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
stringRedisTemplate.delete(key[0]);
} else {
redisTemplate.delete(CollectionUtils.arrayToList(key));
stringRedisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
@@ -95,7 +97,7 @@ public final class RedisUtil {
* @return 值
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
return key == null ? null : stringRedisTemplate.opsForValue().get(key);
}
/**
@@ -105,9 +107,9 @@ public final class RedisUtil {
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key, Object value) {
public boolean set(String key, String value) {
try {
redisTemplate.opsForValue().set(key, value);
stringRedisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
@@ -123,10 +125,10 @@ public final class RedisUtil {
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key, Object value, long time) {
public boolean set(String key, String value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
stringRedisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
@@ -148,7 +150,7 @@ public final class RedisUtil {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
return stringRedisTemplate.opsForValue().increment(key, delta);
}
/**
@@ -162,7 +164,7 @@ public final class RedisUtil {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
return stringRedisTemplate.opsForValue().increment(key, -delta);
}
// ================================Map=================================
@@ -174,7 +176,7 @@ public final class RedisUtil {
* @return 值
*/
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
return stringRedisTemplate.opsForHash().get(key, item);
}
/**
@@ -184,7 +186,7 @@ public final class RedisUtil {
* @return 对应的多个键值
*/
public Map<Object, Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
return stringRedisTemplate.opsForHash().entries(key);
}
/**
@@ -196,7 +198,7 @@ public final class RedisUtil {
*/
public boolean hmset(String key, Map<String, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
stringRedisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
@@ -214,7 +216,7 @@ public final class RedisUtil {
*/
public boolean hmset(String key, Map<String, Object> map, long time) {
try {
redisTemplate.opsForHash().putAll(key, map);
stringRedisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time);
}
@@ -235,7 +237,7 @@ public final class RedisUtil {
*/
public boolean hset(String key, String item, Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
stringRedisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
@@ -254,7 +256,7 @@ public final class RedisUtil {
*/
public boolean hset(String key, String item, Object value, long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
stringRedisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time);
}
@@ -272,7 +274,7 @@ public final class RedisUtil {
* @param item 项 可以使多个 不能为null
*/
public void hdel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
stringRedisTemplate.opsForHash().delete(key, item);
}
/**
@@ -283,7 +285,7 @@ public final class RedisUtil {
* @return true 存在 false不存在
*/
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
return stringRedisTemplate.opsForHash().hasKey(key, item);
}
/**
@@ -295,7 +297,7 @@ public final class RedisUtil {
* @return
*/
public double hincr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, by);
return stringRedisTemplate.opsForHash().increment(key, item, by);
}
/**
@@ -307,7 +309,7 @@ public final class RedisUtil {
* @return
*/
public double hdecr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by);
return stringRedisTemplate.opsForHash().increment(key, item, -by);
}
// ============================set=============================
@@ -317,9 +319,9 @@ public final class RedisUtil {
* @param key 键
* @return
*/
public Set<Object> sGet(String key) {
public Set<String> sGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
return stringRedisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
@@ -335,7 +337,7 @@ public final class RedisUtil {
*/
public boolean sHasKey(String key, Object value) {
try {
return redisTemplate.opsForSet().isMember(key, value);
return stringRedisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
@@ -349,9 +351,9 @@ public final class RedisUtil {
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSet(String key, Object... values) {
public long sSet(String key, String... values) {
try {
return redisTemplate.opsForSet().add(key, values);
return stringRedisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
@@ -366,9 +368,9 @@ public final class RedisUtil {
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSetAndTime(String key, long time, Object... values) {
public long sSetAndTime(String key, long time, String... values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
Long count = stringRedisTemplate.opsForSet().add(key, values);
if (time > 0) {
expire(key, time);
}
@@ -387,7 +389,7 @@ public final class RedisUtil {
*/
public long sGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
return stringRedisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
@@ -403,7 +405,7 @@ public final class RedisUtil {
*/
public long setRemove(String key, Object... values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
Long count = stringRedisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
@@ -420,9 +422,9 @@ public final class RedisUtil {
* @param end 结束 0 到 -1代表所有值
* @return
*/
public List<Object> lGet(String key, long start, long end) {
public List<String> lGet(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
return stringRedisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
@@ -437,7 +439,7 @@ public final class RedisUtil {
*/
public long lGetListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
return stringRedisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
@@ -453,7 +455,7 @@ public final class RedisUtil {
*/
public Object lGetIndex(String key, long index) {
try {
return redisTemplate.opsForList().index(key, index);
return stringRedisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
@@ -467,9 +469,9 @@ public final class RedisUtil {
* @param value 值
* @return
*/
public boolean lSet(String key, Object value) {
public boolean lSet(String key, String value) {
try {
redisTemplate.opsForList().rightPush(key, value);
stringRedisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
@@ -485,9 +487,9 @@ public final class RedisUtil {
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, Object value, long time) {
public boolean lSet(String key, String value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
stringRedisTemplate.opsForList().rightPush(key, value);
if (time > 0) {
expire(key, time);
}
@@ -505,9 +507,9 @@ public final class RedisUtil {
* @param value 值
* @return
*/
public boolean lSet(String key, List<Object> value) {
public boolean lSet(String key, List<String> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
stringRedisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
@@ -523,9 +525,9 @@ public final class RedisUtil {
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, List<Object> value, long time) {
public boolean lSet(String key, List<String> value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
stringRedisTemplate.opsForList().rightPushAll(key, value);
if (time > 0) {
expire(key, time);
}
@@ -544,9 +546,9 @@ public final class RedisUtil {
* @param value 值
* @return
*/
public boolean lUpdateIndex(String key, long index, Object value) {
public boolean lUpdateIndex(String key, long index, String value) {
try {
redisTemplate.opsForList().set(key, index, value);
stringRedisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
@@ -564,7 +566,7 @@ public final class RedisUtil {
*/
public long lRemove(String key, long count, Object value) {
try {
return redisTemplate.opsForList().remove(key, count, value);
return stringRedisTemplate.opsForList().remove(key, count, value);
} catch (Exception e) {
e.printStackTrace();
return 0;

View File

@@ -54,7 +54,7 @@ public class CasController {
break;
}
}
Map<Object, Object> hashMap = (Map<Object, Object>) redisUtil.hget("session", token);
Map<Object, Object> hashMap = (Map<Object, Object>) redisUtil.get("session:"+token);
AssertionImpl assertion = (AssertionImpl) hashMap.get("_const_cas_assertion_");
AttributePrincipal attributePrincipal = assertion.getPrincipal();
Map<String, Object> user = attributePrincipal.getAttributes();
@@ -83,8 +83,8 @@ public class CasController {
Cookie cookie = new Cookie("X-Access-Token", null);
cookie.setMaxAge(0);
String headerToken = request.getHeader("X-Access-Token");
redisUtil.hdel("session", token);
redisUtil.hdel("session", headerToken);
redisUtil.del("session:"+ token);
redisUtil.del("session:"+ headerToken);
Subject subject = SecurityUtils.getSubject();
subject.logout();
return ResultVO.getSuccess(casClientConfigurationProperties.getServerUrlPrefix()+"/logout");