我想拦截请求,并使用伪装的RequestInterceptor将access_token添加到标头中。 但是,当我在拦截器中调试时,我无法获取属性。它是空的。 我怎么才能得到它?
@Override
public void apply(RequestTemplate requestTemplate) {
//the attributes is null, what happened
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
.getRequestAttributes();
if(ObjectUtil.isNull(attributes))
{
return;
}
HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
if(ObjectUtil.isNull(request))
{
return;
}
if(request.getRequestURI().contains(SecurityConstants.MOBILE_TOKEN_URL))
{
requestTemplate.header("x-access-type", SecurityConstants.ACCESS_TYPE_PATIENT);
return;
}
if(request.getRequestURI().contains(SecurityConstants.REGISTER_TOKEN_URL))
{
requestTemplate.header("x-access-type", SecurityConstants.ACCESS_TYPE_PATIENT);
return;
}
Enumeration<String> headerNames = request.getHeaderNames();
if (ObjectUtil.isNotNull(headerNames)) {
while (headerNames.hasMoreElements()) {
String name = headerNames.nextElement();
if(name.equalsIgnoreCase("Authorization")) {
String values = request.getHeader(name);
requestTemplate.header(name, values);
break;
}
}
}
}
答案 0 :(得分:0)
您的问题是使用servlet上下文而不是Feign requestTemplate来获取请求。
此:
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
.getRequestAttributes();
// other code to check and manipulate it
应该是这样
requestTemplate.url().contains("SOME_URL_FOR_TRIGGER") {
requestTemplate.header("YOUR_HEADER", "YOUR_VALUE");
}