其他分享
首页 > 其他分享> > Feign的拦截器,用于在微服务间使用feign远程调用其他微服务时,传递令牌

Feign的拦截器,用于在微服务间使用feign远程调用其他微服务时,传递令牌

作者:互联网

package com.changgou.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestAttribute;
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;
import java.util.Enumeration;

@Component
public class FeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        //传递令牌
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if(requestAttributes != null){
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            if(request != null){
                Enumeration<String> headerNames = request.getHeaderNames();
                while (headerNames.hasMoreElements()){
                    String headerName = headerNames.nextElement();
                    if("authorization".equals(headerName)){
                        String headerValues = request.getHeader(headerName);//得到的内容为 Bearer jwt令牌
                        //传递令牌
                        requestTemplate.header(headerName,headerValues);
                    }

                }
            }
        }

    }
}

使用时直接放在工程中即可,建议放在公共模块,并用其他模块引入公共模块

1

1

 

标签:web,Feign,拦截器,headerName,request,feign,springframework,org,import
来源: https://www.cnblogs.com/wrc-blog/p/14303132.html