Skip to content

OpenFeign 传递请求头

  • OpenFeign 默认不会传递请求头

配置

java
package cloud.xuxiaowei.openfeign.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 请求 授权 拦截器
 * <p>
 * 用于 feign 调用时,传递请求头中 Authorization
 *
 * @author xuxiaowei
 * @since 0.0.1
 */
@Slf4j
public class AuthorizationRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = servletRequestAttributes.getRequest();

        template.header(HttpHeaders.AUTHORIZATION, request.getHeader(HttpHeaders.AUTHORIZATION));
    }

}

使用

java
package cloud.xuxiaowei.api.passport.openfeign;

import cloud.xuxiaowei.openfeign.interceptor.AuthorizationRequestInterceptor;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.Map;

/**
 * 登录授权服务 {@link FeignClient}
 * <p>
 * 如果存在多个 {@link FeignClient#value()} 相同的配置,需要给每个 {@link FeignClient#contextId()} 设置不同的值
 *
 * @author xuxiaowei
 * @since 0.0.1
 */
@FeignClient(value = "xuxiaowei-passport", configuration = {AuthorizationRequestInterceptor.class})
public interface PassportOAuth2FeignClient {

    @GetMapping("/.well-known/oauth-authorization-server")
    Map<String, Object> oauthAuthorizationServer();

}