先写一下流程:
1、服务提供端
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
yml
spring:
security:
user:
name: root
password: root
2、消费端
配置文件中加入head的bean
@Bean
public HttpHeaders getHeaders(){
HttpHeaders heads = new HttpHeaders();
String auth = "root:root";
byte[] enAuth = Base64.getEncoder().encode(auth.getBytes(Charset.forName("US-ASCII")));
String authHeader = "Basic "+new String (enAuth);
heads.set("Authorization",authHeader);
return heads;
controler层改
@RequestMapping("/getById")
public Product getProduct(String id){
Product product = restTemplate.exchange(PRODUCT_GET_URL + id,HttpMethod.GET,
new HttpEntity<Object>(httpHeaders), Product.class).getBody();
return product;
}