package cn.datax.common.security.feign;

import cn.datax.common.core.DataConstant;
import com.google.common.net.HttpHeaders;
import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.util.Base64Utils;

@Configuration
public class DataFeignRequestInterceptor {

    @Bean
    public RequestInterceptor oauth2FeignRequestInterceptor() {
        return requestTemplate -> {
            // 请求头中添加 Gateway Token
            String zuulToken = new String(Base64Utils.encode(DataConstant.Security.TOKENVALUE.getVal().getBytes()));
            requestTemplate.header(DataConstant.Security.TOKENHEADER.getVal(), zuulToken);
            // 请求头中添加原请求头中的 Token
            Object details = SecurityContextHolder.getContext().getAuthentication().getDetails();
            if (details instanceof OAuth2AuthenticationDetails) {
                String authorizationToken = ((OAuth2AuthenticationDetails) details).getTokenValue();
                requestTemplate.header(DataConstant.Security.AUTHORIZATION.getVal(), DataConstant.Security.TOKENTYPE.getVal() + authorizationToken);
            }
        };
    }
}
