package digital.laboratory.platform.inspection.Interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;

/**
 * Feign 请求拦截器
 * Feign Client 向业务系统发出请求的时候, 把 Token 带上, 以用户自己的身份调用业务系统。
 * 目的是在业务系统中识别用户是谁, 允许或禁止用户进行对应的操作。
 */


@Configuration
public class FeignOauth2RequestInterceptor implements RequestInterceptor {

	private final String AUTHORIZATION_HEADER = "Authorization";
	private final String BEARER_TOKEN_TYPE = "Bearer";

	@Override
	public void apply(RequestTemplate requestTemplate) {
System.out.println(String.format("dlp-entrustment, FeignOauth2RequestInterceptor()..."));
		SecurityContext securityContext = SecurityContextHolder.getContext();
		Authentication authentication = securityContext.getAuthentication();
		if (authentication != null && authentication.getDetails() instanceof OAuth2AuthenticationDetails) {
			OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
System.out.println(String.format("FeignOauth2RequestInterceptor() Authorization, token=%s", details.getTokenValue()));
			requestTemplate.header(AUTHORIZATION_HEADER, String.format("%s %s", BEARER_TOKEN_TYPE, details.getTokenValue()));
		}

	}
}

