spring cloud 微服务调用微服务未认证解决方案(Feign)
响应异常:{"error":"unauthorized","error_description":"Full authentication is required to access thisresource"}当实现了用户携带身份令牌访问微服务之后,微服务直接的访问调用就会抛出未授权的异常,,解决方案 服务直接调用时携带令牌Feign 拦截器添加依...
·
响应异常:
{"error":"unauthorized","error_description":"Full authentication is required to access thisresource"}
当实现了用户携带身份令牌访问微服务之后,
微服务直接的访问调用就会抛出未授权的异常,,解决方案 服务直接调用时携带令牌
Feign 拦截器
添加依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>1.4.4.RELEASE</version>
</dependency>
创建拦截器
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
public class FeignClientInterceptor implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
//拦截器
//使用RequestContextHolder工具获取request相关变量
try {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes != null){
// 取出request
HttpServletRequest request = attributes.getRequest();
// 取出所有请求头
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()){
String name = headerNames.nextElement(); // key
String value = request.getHeader(name); //value
if(name.equals("authorization")){ //auoth2 认证请求头
//System.out.println("name="+name+"values="+values);
requestTemplate.header(name, value);
}
}
}
}catch (Exception e){
}
}
}
使用feign
在 springboot 启动类中配置feign拦截器
// 配置feign拦截器
@Bean
public FeignClientInterceptor feignClientInterceptor(){
return new FeignClientInterceptor();
}
然后就行了
更多推荐
已为社区贡献4条内容
所有评论(0)