陈同学
微服务
Accelerator
About
# Eureka安全访问 > 转载自: [3号攻城狮 | Eureka安全访问](https://cloud.tencent.com/developer/article/1121535) ## 背景 在使用注册服务的时候,我们启动了Eureka Server,然后在浏览器中输入http://ip:port/ 后,直接回车,就进入了Spring Cloud的服务治理页面。 在公网部署应用存在以下问题: 1.普通用户可以直接访问我们的服务治理页面 2.普通用户可以将自己的服务注册到生成环境 ## 解决方案 **添加spring-security支持** ```java <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` **在配置文件bootstrap.yml加入安全认证** ```yaml spring: profiles: default cloud: config: enabled: false # 安全认证的配置 security: basic: enabled: true user: name: pikachu # 用户名 password: pikachu # 用户密码 eureka: instance: preferIpAddress: true leaseRenewalIntervalInSeconds: 1 leaseExpirationDurationInSeconds: 3 client: registerWithEureka: false fetchRegistry: false serviceUrl: defaultZone: ${EUREKA_DEFAULT_ZONE:http://pikachu:pikachu@localhost:8761/eureka/ } registryFetchIntervalSeconds: 1 server: evictionIntervalTimerInMs: 1000 ``` 关键配置 ```yaml security: basic: enabled: true user: name: pikachu # 用户名 password: pikachu # 用户密码 ``` ```yaml defaultZone: ${EUREKA_DEFAULT_ZONE:http://pikachu:pikachu@localhost:8761/eureka/} ``` **启动应用查看效果**  输入密码后可以正常访问页面  **正常服务注册效果比较** 使用默认配置做服务注册,可以看到服务注册失败。  调整配置后可以看到,服务正常启动  正常注册  ## 优化 上述解决方案虽然解决了我们公网部署,生产环境部署的安全访问问题。但是针对团队内部的权限依然没有管理好。 通常我们的服务配置存放在两个地方: ``` 1.application.yml 2.bootstrap.yml ``` 项目都能从两个文件中读取配置。但是bootstrap.yml优先于application.yml加载,会初始化系统的环境配置信息。 当使用Spring Cloud时,通常从服务器加载不同环境的配置数据。为了获取URL(和其他连接配置,如密码等),我们就需要一个较早的或“bootstrap”配置。因此,我们可以将配置服务器属性放在bootstrap.yml中,该属性用于加载实际配置数据(通常覆盖application.yml 如果存在中的内容)。 Spring cloud 我们通常都会有config服务。通过config服务读取各个环境的配置信息,所有我们只需要在bootstrap.yml中配置信息来源。将具体的配置写入到application.yml中。 bootstrap.yml如下 ```yml spring: profiles: uat cloud: config: label: master name: cloud-demo-server discovery: serviceId: cloud-config-server enabled: true failFast: true retry: maxAttempts: 32 multiplier: 1.5 maxInterval: 10000 ``` application.yml如下 ``` spring: profiles: default cloud: config: enabled: false # 安全认证的配置 security: basic: enabled: true user: name: pikachu # 用户名 password: pikachu # 用户密码 eureka: instance: preferIpAddress: true leaseRenewalIntervalInSeconds: 1 leaseExpirationDurationInSeconds: 3 client: registerWithEureka: false fetchRegistry: false serviceUrl: defaultZone: ${EUREKA_DEFAULT_ZONE:http://pikachu:pikachu@localhost:8761/eureka/ } registryFetchIntervalSeconds: 1 server: evictionIntervalTimerInMs: 1000 ``` 当然,在一些情况上不用我们不用那么区分这两个文件,只需要使用application文件即可,把全部选项都写在这里,效果基本是一致的,在不考虑上面的加载顺序覆盖的问题上。 ## 总结 通过以上配置我们基本能解决Eureka的安全访问问题: 1.普通用户可以直接通过域名访问我们的服务治理页面; 2.普通用户可以将自己的服务注册到生产环境; 3.团队内部成员权限隔离
本文由
cyj
创作,可自由转载、引用,但需署名作者且注明文章出处。
文章标题:
Eureka安全访问
文章链接:
https://chenyongjun.vip/articles/30
扫码或搜索 cyjrun 关注微信公众号, 结伴学习, 一起努力