SpringCloud实战三:Spring Cloud Eureka 配合 Security 提高安全

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhuyu19911016520/article/details/84895375

  上篇《SpringCloud实战二:Spring Cloud Eureka 服务发现与注册中心》搭建了一个简单的注册中心,启动项目后任何人都可以访问 http://localhost:10025/ eureka注册中心,暴露所有注册的服务IP与端口,虽然 eureka往往隐藏在网关后的内网,但也是不安全的
  引入 spring-cloud-starter-security,配置用户名和密码,访问注册中心时只有知道用户名和密码的用户才能登录,相对提高了注册中心的安全性

1.在上篇项目的基础上,在 eureka-server 项目的 pom.xml 中添加依赖:
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-security</artifactId>
</dependency>

然后在 application.properties 中加入security的用户名和密码配置:

server.port=10025
eureka.instance.hostname=localhost
eureka.instance.prefer-ip-address=true
eureka.client.registerWithEureka=false
eureka.client.fetchRegistry=false
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/

#配置登录的用户名和密码
spring.security.user.name=zy
spring.security.user.password=zy123

再添加一个WebSecurityConfig.java类,因为新版的security默认启用了csrf检验,要在eureka-server服务端配置security的csrf检验为false,eureka-client才能注册,而且它还不支持在配置文件中配置,代码如下:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
    }
}

此时启动 eureka-server,再访问 http://localhost:10025/ ,会发现页面要你输入帐号才能登录,用户名和密码就是上面配置文件中配置的 zy 123456,输入后, 进入熟悉的注册中心
在这里插入图片描述

2.此时再启动 eureka-client ,会发现控制台已经输出了一些错误信息,提示未发现server,明明是 localhost:10025,怎么会找不到,因为 eureka-server 配置了进入的帐号和密码,因此 eureka-client 向 eureka-server 注册时,也要携带 帐号和密码才能注册

在这里插入图片描述

修改eureka-client 的application.properties配置文件,配置如下:

server.port=9600
spring.application.name=eureka-client
eureka.instance.prefer-ip-address=true

#配置eureka-server security的账户信息
eureka.client.serviceUrl.defaultZone=http://zy:zy123@localhost:10025/eureka/

再启动 eureka-client,刷新注册中心 http://localhost:10025,看到 eureka-client 正常注册到注册中心了
在这里插入图片描述

好了,本篇主要是给 eureka 注册中心设置个登录帐号,指定帐号才能登录,提高安全性

猜你喜欢

转载自blog.csdn.net/zhuyu19911016520/article/details/84895375