1.通过feignConfig配置文件来携带用户信息。
2.@FeignClient(name = "user-server", configuration = {FeignConfig.class})
3.feignConfig是实现了请求拦截器的,他可以把用户信息放到requestTemplate中。在header里面放一个key(user-info)
,value是用户信息。
4.服务端,feign实现了应用程序拦截器HandlerInterceptor 。他将拦截请求,在request的header中取出key(user-info),如果错误就返回请求。如果成功就通过。
@Configuration
@Slf4j
public class FeignConfig implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
HttpServletRequest request = getServletRequest();
if (null == request) {
return;
}
UserInfo user = (UserInfo) SecurityUtils.getSubject().getPrincipal();
if (user != null) {
try {
String userJson = JSON.toJSONString(user);
requestTemplate.header("USER_INFO", new String[]{URLDecoder.decode(userJson, "UTF-8")});
} catch (UnsupportedEncodingException e) {
log.error("用户信息设置错误", e);
}
}
}
private HttpServletRequest getServletRequest() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
}
2.fegin 调用配置,加上配置 configuration = {FeignConfig.class}
@FeignClient(name = "user-server", configuration = {FeignConfig.class})
public interface WebUserClient extends UserClient {
}
3.然后服务方 拦截请求 获取 request.getHeader("USER_INFO") 用户信息
@Slf4j
public class AuthorizationInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
String userJson = request.getHeader("USER_INFO");
if (StringUtils.isNotBlank(userJson)) {
try {
userJson = URLDecoder.decode(userJson, "UTF-8");
UserInfo userInfo = JSON.parseObject(userJson, UserInfo.class);
//将UserInfo放入上下文中
UserContext.set(userInfo);
} catch (UnsupportedEncodingException e) {
log.error("init userInfo error", e);
}
}
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Object o, ModelAndView modelAndView) {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Object o, Exception e) {
//关闭threadLocal
UserContext.remove();
}
}
@Configuration
public class WebInterceptorAdapter implements WebMvcConfigurer {
@Bean
public HandlerInterceptor getTokenInterceptor() {
return new AuthorizationInterceptor();
}
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
AntPathMatcher pathMatcher = new AntPathMatcher();
pathMatcher.setCaseSensitive(false);
configurer.setPathMatcher(pathMatcher);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(getTokenInterceptor());
}