SpringCloud OpenFeign token transfer

The essence of OpenFeign is to call the Controller of the specified service.

For front-end and back-end separation projects, you need to pass the token when calling the Controller.

OpenFeign does not automatically carry the token to access the Controller, so manual transfer is required.

Manual token transfer is relatively simple and only requires a configuration class.

import cn.hutool.core.util.ObjUtil;
import feign.RequestInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;

@Slf4j
@Configuration
public class OpenFeignConfig {
    
    
    
    @Bean
    public RequestInterceptor requestInterceptor() {
    
    
        
        return requestTemplate -> {
    
    

            String token;
            // 请求方
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (ObjUtil.isEmpty(requestAttributes)) {
    
    
                return;
            } else {
    
    
                // 获取请求方token
                HttpServletRequest request = requestAttributes.getRequest();
                token = request.getHeader("Authorization");
            }
            // 被请求方设置token,实现token中转
            requestTemplate.header("Authorization", token);
        };
    }
    
}

Guess you like

Origin blog.csdn.net/qq_37770674/article/details/132849407