使用spring cloud 做微服务时,例如:做A服务时需要通过Feign调用B服务。但是我们的B服务做了某些权限验证。需要验证header或者token什么的。如果某没有token,会被阻止调用。那如何添加token呢。如果每个方法都手动设置headers,那未免太麻烦。可以通过Feign配置,自动帮我们添加请求header。
@Configuration
public class FeignConfig implements RequestInterceptor {
@Value("${superToken:xxxxxxxxxxxxxxxxxxxx}")
private String superToken;
@Bean
Request.Options feignOptions() {
return new Request.Options(30000, 60000);
}
@Bean
public Decoder feignDecoder() {
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
ObjectFactory<HttpMessageConverters> objectFactory = () -> new HttpMessageConverters(
fastConverter);
return new ResponseEntityDecoder(new SpringDecoder(objectFactory));
}
@Override
public void apply(RequestTemplate requestTemplate) {
Map<String, String> headers = getHeaders(getHttpServletRequest());
if (null == headers || !headers.keySet().contains("authorization") || StringUtils
.isEmpty(headers.get("authorization"))) {
requestTemplate.header(XRequestIDFilter.X_REQUEST_ID, UUID.randomUUID().toString());
requestTemplate.header("across_auth", "true");
requestTemplate.header("Authorization", "Bearer " + superToken);
} else {
requestTemplate.header("Authorization", headers.get("authorization"));
requestTemplate.header(XRequestIDFilter.X_REQUEST_ID, headers.get("x-request-id"));
}
}
private HttpServletRequest getHttpServletRequest() {
try {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
} catch (Exception e) {
return null;
}
}
private Map<String, String> getHeaders(HttpServletRequest request) {
if (null == request) {
return null;
}
Map<String, String> map = new LinkedHashMap<>();
Enumeration<String> enumeration = request.getHeaderNames();
while (enumeration.hasMoreElements()) {
String key = enumeration.nextElement().toLowerCase();
String value = request.getHeader(key);
map.put(key, value);
}
return map;
}
}