Feign设置assessToken

首先继承接口RequestInterceptor实现apply方法

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
 
import feign.RequestInterceptor;
import feign.RequestTemplate;
 
/**
 * 
 *用于解决fegin无法传递授权信息
 * @author 	cicoding
 * @date 	2018年5月26日
 * @Copyright 
 *
 * <pre>
 * =================Modify Record=================
 * Modifier			date				Content
 * cicoding		2019年5月26日			 新增
 *
 * </pre>
 */
@Configuration
public class FeignRequestInterceptor implements RequestInterceptor {
    private final Logger logger = LoggerFactory.getLogger(getClass());
 
    private static final String AUTHORIZATION_HEADER = "Authorization";
 
    private static final String BEARER_TOKEN_TYPE = "Bearer";
 
    @Autowired
    private OAuth2RestTemplate oAuth2RestTemplate;
 
    @Override
    public void apply(RequestTemplate requestTemplate) {
        String accessToken = WebContextUtil.getAccessToken();
        if(accessToken == null){
            accessToken =oAuth2RestTemplate.getAccessToken().getValue();
        }
        logger.debug("RequestInterceptorConfig accessToken :" +accessToken);
        requestTemplate.header(AUTHORIZATION_HEADER,
                String.format("%s %s",
                        BEARER_TOKEN_TYPE,
                        accessToken));
    }
}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.client.DefaultOAuth2RequestAuthenticator;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails;
 
/**
 * 
 *用于解决fegin无法传递授权信息
 * @author 	cicoding
 * @date 	2018年5月26日
 * @Copyright 
 *
 * <pre>
 * =================Modify Record=================
 * Modifier			date				Content
 * cicoding			2019年5月26日		新增
 *
 * </pre>
 */
@Configuration
public class OAuth2RestTemplateConfiguration {
    @Bean
    public OAuth2RestTemplate oauth2RestTemplate() {
        ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails();
        resourceDetails.setClientId("webapp");
        resourceDetails.setClientSecret("webapp");
        resourceDetails.setId("service-user");
        resourceDetails.setAccessTokenUri("http://127.0.0.1:9060/oauth/token");
        OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(resourceDetails);
        oAuth2RestTemplate.setAuthenticator(new DefaultOAuth2RequestAuthenticator());
        return oAuth2RestTemplate;
    }
}

FeignRequestInterceptor 和OAuth2RestTemplateConfiguration 类!

posted @ 2021-12-01 14:41  筱进GG  阅读(91)  评论(0编辑  收藏  举报
SpringBoot SpringCloud Docker