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

本贴最后更新于 823 天前,其中的信息可能已经时过境迁

原文发布于:Eureka 添加安全验证的两种方式其一:使用 Spring Security(2022 最新版本),欢迎使用 RSS 订阅获取最新更新。

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}/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

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...