跳到主要内容

Eureka添加安全验证的两种方式其一:使用Spring Security(2022最新版本)

1. 使用Spring Security

已有做好的demo,大家可以自取,链接:https://github.com/MingGH/demo-eureka-server-auth

这里代码使用的依赖版本如下

spring-boot-starter-parent3.0.1
spring-cloud.version2022.0.0
java.version17

开始我们的步骤

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}/eurekadefaultZone [进行特殊配置是因为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 测试效果

启动正常

从面板上看也是正常的,能够成功给自己注册

至此大功告成

1.5 参考以下内容

【security】spring security放行不生效,security放行后还是被拦截,路径变成了/error

Spring Security without the WebSecurityConfigurerAdapter