当咱们直接配置完SpringCloudEureka的时候,任何人直接就能够访问,这样是极不安全的!!外网的状况下是绝对不容许的!
好在有提供了解决方案,下面拿为咱们提供的Security解决web
SpringCloud版本:
<spring-cloud.version>Greenwich.SR4</spring-cloud.version>
注册中心
一、pom文件添加security坐标
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>二、在application.yml文件中添加配置(properties同样,格式稍微变化);若是是集群的话,全部集群配置文件都要修改以下格式
spring: security: #开启安全验证 user: name: root #用户名 password: admin #密码
三、注册地址变为以下格式(service-url.defaultZone);若是是集群的话,全部集群配置文件都要修改以下格式
defaultZone: http://${spring.security.user.name}:${spring.security.user.password}@IP:${server.port}/eureka/ #eureka注册中心地址四、添加一个SpringSecurity配置类
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; @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { super.configure(http);//加这句是为了访问eureka控制台和/actuator时能作安全控制 http.csrf().disable();//关闭csrf } }注册中心完成!看到以下效果即成功
客户端
一、修改application.yml配置文件(service-url.defaultZone) 便可
eureka: client: service-url: defaultZone: http://注册中心配置的用户名:注册中心配置的密码@eureka1:端口/eureka/
下面是个人注册中心配置(集群版,数量为2)
application.eureka1.ymlspring
spring: application: name: eureka-server security: #开启安全验证 user: name: root password: admin server: port: 8761 eureka: instance: hostname: eureka1 #设置eureka实例名,与配置文件的变量为主 client: service-url: defaultZone: http://${spring.security.user.name}:${spring.security.user.password}@eureka2:${server.port}/eureka/ #eureka注册中心地址 # server: # enable-self-preservation: false #关闭自我保护:true开启,false关闭 默认为true # eviction-interval-timer-in-ms: 10000 #扫描清理间隔时间(单位:毫秒 默认是60*1000)
application.eureka2.yml安全
spring: application: name: eureka-server security: #开启安全验证 user: name: root password: admin server: port: 8761 eureka: instance: hostname: eureka2 #设置eureka实例名,与配置文件的变量为主 client: service-url: defaultZone: http://${spring.security.user.name}:${spring.security.user.password}@eureka1:${server.port}/eureka/ #eureka注册中心地址 #server: ## enable-self-preservation: false #关闭自我保护:true开启 false关闭 默认true ## eviction-interval-timer-in-ms: 10000 #清理间隔时间(单位:毫秒 默认60*1000)
客户端配置服务器
spring: application: name: eureka-provider server: port: 9090 eureka: client: service-url: defaultZone: http://root:admin@eureka1:8761/eureka/,http://root:admin@eureka2:8761/eureka/ #设置服务注册中心地址,多个之间用","分割 instance: lease-renewal-interval-in-seconds: 1 #每隔1s发送一次心跳,证实本身还活着 lease-expiration-duration-in-seconds: 2 #告诉服务器若是2s没有发送心跳,就表明死了,将我剔除掉 management: endpoints: web: exposure: include: shutdown #暴漏shutdown端点服务 endpoint: shutdown: enabled: true