Eureka添加安全验证的两种方式其一:使用Spring Security(2022最新版本)
1. 使用Spring Security
已有做好的demo,大家可以自取,链接:https://github.com/MingGH/demo-eureka-server-auth
这里代码使用的依赖版本如下
spring-boot-starter-parent | 3.0.1 |
---|---|
spring-cloud.version | 2022.0.0 |
java.version | 17 |
开始我们的步骤
1.1 pom.xml中添加spring security的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
1.2 yaml配置中添加登录和接口请求需要的账号密码
server:
port: 5005
spring:
application:
name: demo-eureka-server-auth
security:
user:
name: develop # 账号
password: develop # 密码
eureka:
instance:
hostname: localhost
appname: ${spring.application.name}
server:
enable-self-preservation: true
eviction-interval-timer-in-ms: 4000
client:
registerWithEureka: true # 这里我设置为true是因为把当前项目也注册到注册中心,就省了新建一个client项目
fetchRegistry: false
service-url:
defaultZone: http://${spring.security.user.name}:${spring.security.user.password}@${eureka.instance.hostname}:${server.port}/eureka #这里是有更改的,对应的内容是:http://develop:develop@localhost:5005/eureka
environment: dev
在上述配置中需要注意的几个配置,
spring.security.user
账号密码eureka.client.registerWithEureka=true
这里我设置为true是因为把当前项目也注册到注册中心,就省了新建一个client项目eureka.client.service-url.defaultZone=http://${spring.security.user.name}:${spring.security.user.password}@${eureka.instance.hostname}:${server.port}/eureka
对defaultZone
[进行特殊配置是因为spring.security](http://进行特殊配置是因为spring.security)
需要账号密码才能授权请求到对应的接口
1.3 Spring Security关闭csrf
新建一个WebSecurityConfig, 注入spring容器中
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic();
return http.build();
}
}
最后别忘了在启动类上加上注解:@EnableEurekaServer
1.4 测试效果
启动正常
从面板上看也是正常的,能够成功给自己注册
至此大功告成