我们知道feign是HTTP请求的所以有的时候需要添加些头部参数什么的,这些参数通常是通过feign的配置信息来添加的。
例:我们的服务提供者设置了安全校验,需要配置账号、密码才能正式请求。
服务提供者:
1、pom添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2、配置yml
spring:
application:
name: test1
security:
user:
name: root
password: root
3、java设置所有访问都需要安全认证
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//禁用csrf
http.csrf().disable();
// 表示所有的访问都必须认证,认证处理后才可以正常进行
http.httpBasic().and().authorizeRequests().anyRequest().fullyAuthenticated();
// 所有的rest服务一定要设置为无状态,以提升操作效率和性能
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
此时服务消费者调用服务提供者报错:出现401是因为服务提供者设置了请求需要进行认证处理
服务消费者配置认证:
//@Configuration:启用该注解后该类会被所有@feign加载,所以最好不在这里使用
public class FeignAuthConfiguration {
@Bean
public BasicAuthRequestInterceptor basicAuthRequestInterceptor(){
return new BasicAuthRequestInterceptor("root","root");
}
}
调用服务的接口注解上添加该配置类:
//我们每个接口类会调用不同服务的信息,所以configuration对应的类可能会不同
@FeignClient(name = "test1",configuration = FeignAuthConfiguration.class)
public interface FeignTest1Service {
@RequestMapping(value = "/ribbonTest",method = RequestMethod.POST)
public String testFeign(@RequestBody Map<String,String> map);
}
@Configuration:启用该注解后该类会被所有@feign加载,所有@feign都会使用该配置类信息
启动服务消费者再次调用: