Fork me on GitHub

Feign设置assessToken

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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));
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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 类!

相关文章

微信打赏

赞赏是不耍流氓的鼓励

评论系统未开启,无法评论!