首先先介绍一下threadLocal
ThreadLocal
线程局部变量,创建一个线程变量后,针对这个变量可以让每个线程拥有自己的变量副本,每个线程是访问的自己的副本,与其他线程的相互独立。
大致知道threadLocal就可以了,然后我们直接看例子
首先从登录的地方走起,这个只是个简单的设备号登录,账号密码同理,到时候改改就行
@Service
public class UserLoginService {
@Autowired
private UserService userService;
@Resource
private UserLoginConverter userLoginConverter;
@Resource
private UserConverter userConverter;
@Transactional(rollbackFor = Exception.class)
public UserLoginVO login(UserLoginDTO dto) {
UserLoginVO result = new UserLoginVO(SignType.SIGNIN);
User user = userService.findOne(dto.getDeviceNo());
if (Objects.isNull(user)) {
user = userService.save(userLoginConverter.dto2Dto(dto));
result.setSignType(SignType.SIGNUP);
}
UserVO userVO = userConverter.entity2VO(user);
result.setUser(userVO);
result.setToken(UserTokenUtils.create(
new UserToken(user.getId())
));
return result;
}
}
可以看见用户登录以后会制造一个token
UserTokenUtils工具类:
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class UserTokenUtils {
private static final String ID = "id";
private static final String ISSUER = "dreamland";
private static final String TIMESTAMP = "timestamp";
private static final Algorithm ALGORITHM = Algorithm.HMAC256("79cIYsXMF9TLDCPy");
private static Long getExpireTime() {
UserAuthProperties properties = SpringContextHolder.getBean(UserAuthProperties.class);
return properties.getTokenExpire() * 1000L;
}
/**
* 创建Token
*
* @param token
* @return
*/
public static String create(UserToken token) {
Date expiresAt = new Date(System.currentTimeMillis() + getExpireTime());
return JWT.create() //
.withIssuer(ISSUER) // jwt签发者,可选
.withExpiresAt(expiresAt) // 过期时间
.withClaim(ID, token.getId()) // id
.withClaim(TIMESTAMP, token.getTimestamp()) // 时间戳
.sign(ALGORITHM);
}
/**
* 验证Token
*
* @param token
* @return
*/
public static UserToken verify(String token) {
UserToken info = new UserToken();
JWTVerifier verifier = JWT.require(ALGORITHM) // 指定验证算法
.withIssuer(ISSUER) // 要求token必须有指定签发者
.build();
DecodedJWT decode = verifier.verify(token);
info.setId(decode.getClaim(ID).asLong());
info.setTimestamp(decode.getClaim(TIMESTAMP).asLong());
return info;
}
/**
* 通过Token解码
*
* @param token
* @return
*/
public static UserToken decode(String token) {
UserToken info = new UserToken();
DecodedJWT decode = JWT.decode(token);
info.setId(decode.getClaim(ID).asLong());
info.setTimestamp(decode.getClaim(TIMESTAMP).asLong());
return info;
}
}
UserToken 类:
@Data
@NoArgsConstructor
public class UserToken {
private Long id;
private Long timestamp = System.currentTimeMillis();
public UserToken(Long userId) {
this.id = userId;
}
}
我使用的是jwt,因此需要导入一下这个pom依赖
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>${jwt.version}</version>
</dependency>
至此token已经传给了前端,前端每次发送请求都会带上我们的token
然后就需要在拦截器里面做手脚了
UserAuthContextInterceptor拦截器类:
public class UserAuthContextInterceptor extends HandlerInterceptorAdapter {
/**
* 前置拦截
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = null;
// 从请求参数中获取token
token = request.getParameter(UserConsts.HEADER_USER_TOKEN);
// 如果为空从Cookie中获取
Cookie[] cookies = Optional.ofNullable(request.getCookies()).orElse(new Cookie[]{});
List<Cookie> cookieList = Arrays.asList(cookies).stream()
.filter(cookie -> UserConsts.HEADER_USER_TOKEN.equals(cookie.getName())).collect(Collectors.toList());
Cookie cookie = cookieList.isEmpty() ? null : cookieList.get(0);
token = StringUtils.isBlank(token) && Objects.nonNull(cookie) ? cookie.getValue() : token;
// 如果为空从head中获取
token = StringUtils.isBlank(token) ? request.getHeader(UserConsts.HEADER_USER_TOKEN) : token;
if (StringUtils.isBlank(token)) {
throw new JWTVerificationException("The token can not be empty!");
}
// 解析Token信息,并存入UserAuthContext
UserToken userTokenInfo = UserTokenUtils.verify(token);
UserAuthContext.setUserTokenInfo(userTokenInfo);
return true;
}
/**
* 后置拦截
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
UserAuthContext.release();
}
}
可以看见我们在前置拦截器和后置拦截器里面分别调用了
UserAuthContext.setUserTokenInfo(userTokenInfo); 设置当前请求用户的token信息到线程上下文
UserAuthContext.release(); 释放当前线程上下文的用户信息
拦截器会把发来的带有token的请求解析并且存储,然后会在返回响应时将解析存储的用户信息给清理掉,真是万花丛中走片叶不沾身啊。
UserAuthContext类:
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class UserAuthContext {
private static final ThreadLocal<UserToken> CONTEXT = new ThreadLocal<>();
/**
* 获取用户id
*/
public static Long getId() {
return CONTEXT.get().getId();
}
/**
* 获取timestamp
*/
public static Long getTimestamp() {
return CONTEXT.get().getTimestamp();
}
/**
* 设置当前请求用户的token信息到线程上下文
*/
public static void setUserTokenInfo(UserToken info) {
CONTEXT.set(info);
}
/**
* 释放当前线程上下文的用户信息
*/
public static void release() {
CONTEXT.remove();
}
}
这个类里面就包含了存入已经撤销的命令,并且还有获取用户信息的命令,我这里仅仅有用户id
的获取方法
一切准备就绪,但是这样我们自定义的拦截器并不会生效,也就是请求压根不会过我们的拦截器,所以就需要手动配置使用
UserAuthConfig类:
@Configuration
@EnableConfigurationProperties(UserAuthProperties.class)
public class UserAuthConfig implements WebMvcConfigurer {
@Autowired
private UserAuthProperties userAuthProperties;
@Bean
public UserAuthContextInterceptor userActionContextInterceptor() {
return new UserAuthContextInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(userActionContextInterceptor())
.addPathPatterns(userAuthProperties.getPathPatterns())
.excludePathPatterns(userAuthProperties.getExcludePathPatterns());
}
/**
* 静态资源映射
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/swagger-ui/index.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/doc.html/**").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}
}
在拦截器配置里面将我们的拦截器加入使用,同时指定了要拦截和不拦截的路径,不过路径我又封装在了UserAuthProperties类中了
UserAuthProperties类:
@Data
@ConfigurationProperties("user-auth")
public class UserAuthProperties {
/**
* token过期时间(单位:秒) 默认7天
*/
private Long tokenExpire;
/**
* 要拦截的路径
*/
private String[] pathPatterns;
/**
* 不拦截的路径
*/
private String[] excludePathPatterns;
}
可能有些人会疑惑,这个过期时间没咋个看见用,其实是用了的,不过我忘记说了,fack。
已经在UserTokenUtils创建token的时候调用了一个getExpireTime()方法,里面有一句是这样的:
UserAuthProperties properties = SpringContextHolder.getBean(UserAuthProperties.class);
return properties.getTokenExpire() * 1000L;
通过 SpringContextHolder 工具类获取名为 UserAuthProperties
的 Bean 对象。并且拿到里面的tokenExpire值,看,是不是重新连起来了
这个类也放出来
SpringContextHolder类:
@Configuration
public class SpringContextHolder implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static Object getBean(String beanName) {
checkContext();
return context.getBean(beanName);
}
public static <T> T getBean(String beanName, Class<T> clazz) {
checkContext();
return context.getBean(beanName, clazz);
}
public static <T> T getBean(Class<T> clazz) {
checkContext();
return context.getBean(clazz);
}
private static void checkContext() {
if (Objects.isNull(context)) {
throw new RuntimeException("The applicationContext is not initialized!");
}
}
}
重新回归正题,那我们的路径是从UserAuthProperties类中拿的,那这个类得数据又是哪里来的?其实UserAuthProperties类中有个注解@ConfigurationProperties("user-auth"),就是从我们得配置文件得user-auth中读取数据
我的application.xml:
server:
# 开启优雅关闭
shutdown: graceful
# gzip压缩
compression:
enabled: true
min-response-size: 2048
mime-types: text/plain,text/xml,application/xml,application/json
port: 8160
spring:
lifecycle:
# 关闭的缓冲时间
timeout-per-shutdown-phase: 30s
application:
name: iverify-client
profiles:
active: local
servlet:
multipart:
max-file-size: 50MB
max-request-size: 100MB
user-auth:
token-expire: 31536000
path-patterns:
- /v1/**
exclude-path-patterns:
- /swagger-resources/**
- /webjars/**
- /v2/**
- /swagger-ui.html/**
- /doc.html/**
- /error
- /favicon.ico
- /v1/health
- /v1/user-login/device
- /v1/face-compare-results/watermark
- /v1/user/queryUser
- /v1/avatar-compare-results/query
其他配置不用关注,只看user-auth就好,至此数据顺利过通。
小小总结一下,其实就是用户登录得时候创建了一个token,里面包含了用户得信息。我们后端在用户登录成功后把token放给前端,前端拿着token访问我们接口。访问接口得请求就会被我们得拦截器拦住,拦截器对token进行解析和存入threadLocal中,在请求走完通过后置拦截器来注销保存得用户信息。
使用:
直接调用getId()就可以轻松拿到用户id了,方方便便轻轻松松