spring cloud Feign oauth2令牌传递

创建feign的配置类

/**
 * Feign配置
 **/
@Configuration
public class FeignConfiguration {
    /**
     * 日志级别
     * @return
     */
	@Bean  
    Logger.Level feignLoggerLevel() {  
        return Logger.Level.FULL;  
    }

    /**
     * 创建Feign请求拦截器,在发送请求前设置认证的token,各个微服务将token设置到环境变量中来达到通用
     * @return
     */
    @Bean
    public FeignBasicAuthRequestInterceptor basicAuthRequestInterceptor() {
        return new FeignBasicAuthRequestInterceptor();
    }

}

创建feign拦截器,传递令牌

/**
 * Feign请求拦截器
 **/
public class FeignBasicAuthRequestInterceptor  implements RequestInterceptor {

    public FeignBasicAuthRequestInterceptor() {

    }

    @Override
    public void apply(RequestTemplate template) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            //添加token
            template.header(HttpHeaders.AUTHORIZATION, request.getHeader(HttpHeaders.AUTHORIZATION));
    }
}

将feign配置加到feign接口的注解中

@FeignClient(name = "microservice-provider-user", configuration = FeignConfiguration.class)

你可能感兴趣的:(Java学习笔记,SpringCloud,springboot)