Spring Cloud Netflix 服务发现:Eureka (二) 身份验证

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

部分内容摘自Spring Cloud 官方文档中文版

本文源码地址:https://github.com/Wyxwx/SpringCloudDemo

成功启动 Eureka 服务器之后,任意一个浏览器只要知道服务器的 ip 和端口号便可以直接进入

这样会带来严重的安全隐患,并且在服务中心界面也会有安全隐患提示,所以 Eureka 提供了身份验证功能

该功能基于 Spring Security 组件的登录功能

接下来,基于Spring Cloud Netflix 服务发现:Eureka (一) 注册和运行 进行改写

在 eureka_server 的 pom.xml 中添加 Spring Security 依赖


        <!-- 身份验证模块所用 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
            <version>2.1.4.RELEASE</version>
        </dependency>

Spring Security 会默认开启 CSRF(跨站请求伪造)防护,而 Eureka 客户端没有有效的 CSRF 令牌,所以需要在配置中忽略对 Eureka 的拦截

扫描二维码关注公众号,回复: 6103811 查看本文章
package com.example.demo.config;

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 SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().ignoringAntMatchers("/eureka/**");
        super.configure(http);
    }
}

修改配置文件,添加登录验证信息,并修改 eureka.client.service-url.defaultZone ,此时,HTTP基本身份验证将自动添加到eureka客户端

server.port=8761

# Eureka Server 自己的 IP 地址
eureka.instance.hostname=localhost

# 默认值都为 true
# 为 true 时代表注册为客户端
# 此时注册为服务端,所以都改为 false
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

#eureka.client.service-url.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/
# 开启身份验证
eureka.client.service-url.defaultZone=http://${spring.security.user.name}:${spring.security.user.password}@${eureka.instance.hostname}:${server.port}/eureka/

# 设置登录账号和密码
spring.security.user.name=wyx
spring.security.user.password=123456

启动 eureka_server 的启动类并访问 http://localhost:8761 利用账号密码登录成功后进入到服务中心页面

此时服务端开启成功验证功能,但是还需要对客户端进行改写,否则无法在服务中心注册

修改 eureka_client 配置文件并重启客户端启动类(若是不修改客户端,则客户端启动类启动后会报错)

server.port=8762

# 为客户端提供服务 URL
#eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
eureka.client.service-url.defaultZone=http://wyx:123456@localhost:8761/eureka/

#默认应用程序名称(服务ID)
spring.application.name=provideHelloService

再次访问服务中心页面,发现客户端成功注册

 访问 http://localhost:8762/hi 成功访问

猜你喜欢

转载自blog.csdn.net/Wyx_wx/article/details/89285744