基于SpringBoot 2.X整合Spring Security

说明:本文旨在整理SpringBoot 2.X整合Spring Security基础功能,如有问题请指出


一. 在Eureka Server的pom.xml文件中引入Spring Security的依赖

楼主这里引入的是org.springframework.cloud的依赖包

	   <!-- Security -->
       <dependency>
           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-starter-security</artifactId>
       </dependency>

二. 配置Eureka Server的application.yml文件

基于SpringBoot 1.X版本是如下配置:
security.basic.enabled: true
security.user.name=admin
security.user.password=12345
基于SpringBoot 2.x版本将security属性移入到spring配置里,且basic.enabled属性无效
spring.security.user.name=admin
spring.security.user.password=12345

spring:
 application:
   name: eureka-server
 security:
   user:
     name: admin
     password: 12345

server:
 port: 8761

eureka:
 instance:
   hostname: localhost
   prefer-ip-address: true
 client:
   registerWithEureka: false
   fetchRegistry: false
   serviceUrl:
     defaultZone: http://admin:[email protected]${eureka.instance.hostname}:${server.port}/eureka/

三. 在Eureka Server中增加WebSecurityConfig类

该类继承WebSecurityConfigurerAdapter重写 configure(HttpSecurity http)方法,关闭csrf检验
若不配置WebSecurityConfig,则服务无法向Eureka注册中心进行注册,且抛出Cannot execute request on any known server异常,如下图
基于SpringBoot 2.X整合Spring Security

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().anyRequest().authenticated().and().httpBasic();
    }
}

四. 修改Eureka Client的application.yml文件

Eureka Client的yml配置增加Eureka Server的账号密码

eureka:
client:
  serviceUrl:
    defaultZone: http://admin:[email protected]:8761/eureka/

五. 启动测试

  1. 启动Eureka Server服务,访问http://localhost:8761/,这时会要求输入上面配置的账号密码admin/12345
    基于SpringBoot 2.X整合Spring Security
  2. 登录成功后启动Eureka Client服务
    基于SpringBoot 2.X整合Spring Security
  3. Eureka Client服务启动成功后刷新http://localhost:8761/,就可以看到服务注册成功了
    基于SpringBoot 2.X整合Spring Security

参考资料:
https://blog.csdn.net/u010391342/article/details/83086519
https://blog.csdn.net/m_sophia/article/details/80868121

相关文章:

  • 2019-11-06
  • 2018-06-24
  • 2019-10-23
  • 2021-11-02
  • 2019-08-12
  • 2020-01-13
  • 2018-12-24
  • 2019-10-10
猜你喜欢
  • 2020-01-08
  • 2021-08-11
  • 2020-01-04
  • 2018-12-24
  • 2021-02-03
  • 2018-07-23
  • 2018-04-07
  • 2019-06-29
相关资源
相似解决方案