spring cloud Feign oauth2令牌传递

Posted nnsword

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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)

以上是关于spring cloud Feign oauth2令牌传递的主要内容,如果未能解决你的问题,请参考以下文章

19 张思维导图学习 Spring Cloud

Spring Cloud Feign 组成和配置

6Sping Cloud Feign

spring cloud feign遇到的问题

Spring-Cloud之Feign

如何使用 Spring Boot feign 客户端进行 Oauth2 身份验证?