一、简介

在《Spring Cloud教程 | 第一篇:Eureka 服务的注册与发现(Eureka Server与Eureka Client)》
<https://blog.csdn.net/liujun19921020/article/details/88853563>
中讲述了如何将服务通过各注解、依赖包、application.yml配置注入到注册中心的过程


但是,有群闲的蛋疼的二货,故意在EurekaClient端将莫名其妙的服务注入进来,当然,或许有些不是故意的,但就怕巧合,刚好将注入地址写成了你的IP端口,那咋办,就木有一点保护措施的吗?没有是不可能的!下面来讲讲Eureka
Server的用户安全认证。

服务注入注册中心写法回顾(无保护时defaultZone属性极易出问题):
eureka.client.serviceUrl.defaultZone: http://localhost:8761/eureka/
 

本章案例 源码下载:链接: https://pan.baidu.com/s/1oahimLg39HnAT0Q8KRa8oQ
<https://pan.baidu.com/s/1oahimLg39HnAT0Q8KRa8oQ> 提取码: awer

或github下载:
https://github.com/liujun19921020/SpringCloudDemo/tree/master/ProjectDemo/sc-finchley-demo2-Eureka%E5%AE%89%E5%85%A8%E8%AE%A4%E8%AF%81/sc-finchley-demo2

<https://github.com/liujun19921020/SpringCloudDemo/tree/master/ProjectDemo/sc-finchley-demo2-Eureka%E5%AE%89%E5%85%A8%E8%AE%A4%E8%AF%81/sc-finchley-demo2>

 

二、 Eureka Server加用户安全认证

这一篇文章基于上一篇文章的工程做改进说明即可

2.1 改造eureka-server工程

添加spring-security支持并在配置文件中加入安全认证

2.1.1 pom.xml中添加依赖
<dependency> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId> </dependency>
2.1.2 application.yml加入安全认证配置(eureka.client.serviceUrl.defaultZone属性也有更改)
server: port: 8761 eureka: instance: hostname: localhost client: #声明自己是服务端
registerWithEureka: false fetchRegistry: false serviceUrl: defaultZone:
http://user:123456@${eureka.instance.hostname}:${server.port}/eureka/ spring:
application: name: eureka-server # 安全认证的配置 security: basic: enabled: true #开启认证
user: name: user password: 123456
2.1.3 关闭csrf——划重点啦,新版本的security默认开启csrf了,一定要关掉
,新建一个配置类(这一步不做的话,注册中心能启动,但是服务无法注册进来的啊!!)
@EnableWebSecurity @Configuration public class WebSecurityConfig extends
WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity
http) throws Exception { http.csrf().disable(); //关闭csrf
http.authorizeRequests().anyRequest().authenticated().and().httpBasic(); //开启认证
} }
 

2.2 改造service-hi(Eureka Client)工程

这里没改啥,就把application.yml注册时,eureka.client.serviceUrl.defaultZone加上账号密码就成
server: port: 8762 spring: application: name: service-hi eureka: client:
serviceUrl: defaultZone: http://user:123456@localhost:8761/eureka/
 

 

好了,成功了!!!

依次启动eureka-server 工程、service-hi工程

输入注册中心地址http://localhost:8761/ <http://localhost:8761/>界面查看时,需要授权登录,然后进入





 

 

OK!用户安全中心完成!

友情链接
ioDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:637538335
关注微信