SpringCloud Eureka 服务注册中心5:配置账号密码

原创
2021/07/05 14:41
阅读数 570

小伙伴肯定有疑惑了,只要知道地址是不是谁都可以往注册中心注册了,以及访问注册页面了。那也太不安全了吧。针对种情况,我们有很多解决方案,Spring Cloud Eureka 也支持设置账号密码,而这里主要用到的就是 Spring Security 做安全认证。

 

一、准备工作

1.1、创建一个注册中心-服务端

请参考:Spring Cloud Eureka 服务注册中心1:服务的注册与发现

这里我们创建了一个注册中心:piao-server

1.2、创建一个注册中心-客户端(提供者)

请参考:Spring Cloud Eureka 服务注册中心1:服务的注册与发现

这里我们创建了一个服务提供者:piao-client

 

二、配置注册中心账号密码

2.1、添加依赖

这里我们需要设置注册中心服务端访问账号和密码。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

 

2.2、添加配置

在 application.properties 加入认证的用户名和密码:

spring.security.user.name=piao
spring.security.user.password=123456

关闭 Spring Security 的 CSRF 验证。如果不关闭,那么客户端就连接不上。

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable(); //关闭csrf
        super.configure(http);
    }
}

现在我们启动注册中心服务端,来访问我们的注册中心的页面。

请求地址:http://127.0.0.1:2000

输入我们配置的账号和密码:piao/123456。

 

三、客户端连接注册中心

因为我们注册中心服务端设置账号密码,现在我们客户端连接的时候就需要通过账号密码连接了。

在 application.properties 加入认证的用户名和密码:

eureka.client.serviceUrl.defaultZone=http://piao:123456@localhost:2000/eureka/

现在我们启动客户端。

访问注册中心页面地址:

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部