需求: 搭建Spring Cloud Eureka集群,注册中心使用Spring Security 密码验证
spring boot version :
2.1.2.RELEASE
spring cloud version:
Greenwich.RELEASE
启动类添加注释:
@EnableEurekaServer
两个application.yml,分别命名为
application-peer1.yml和application-peer2.yml
内容分别为
server:
port: 5567
spring:
application:
name: register
security:
user:
name: admin
password: admin
eureka:
instance:
hostname: peer1
client:
fetch-registry: false
register-with-eureka: false
service-url:
defaultZone: http://admin:admin@peer2:5568/eureka/
---------------------------------------------------------------------------------------
server:
port: 5568
spring:
application:
name: register
security:
user:
name: admin
password: admin
eureka:
instance:
hostname: peer2
client:
fetch-registry: false
register-with-eureka: false
service-url:
defaultZone: http://admin:admin@peer1:5567/eureka/
(注:hosts文件要配置peer1,peer2和127.0.0.1的映射)
关键步骤:
这个版本的security 会默认进行csrf攻击防御,我选择直接关闭防御。(如何针对防御进行配置,而不是简单的关闭呢)
@EnableWebSecurity
public class WebConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// 去掉security 的csrf验证,否则其他应用无法使用账号密码连接注册中心
System.err.println("取消security csrf验证");
http.csrf().disable();
super.configure(http);
}
}
更好的办法是,我们保留csrf防御,只将eureka注册的请求忽略掉就好
@EnableWebSecurity
public class WebConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// 更好的办法是,配置/eureka/**忽略csrf防御拦截,直接放行(/eureka/**是在application.yml中配置的eureka注册地址)
http.csrf().ignoringAntMatchers("/eureka/**");
super.configure(http);
}
}
(csrf是跨站伪造请求的意思)
本地运行配置:
然后可以依次运行两个配置,浏览器输入注册中心地址,发现两个都注册成功
打包运行方式为在java -jar ...命令最后添加指定application.yml版本的语句,见上图。