SpringSecurity是Spring下的一个安全框架,与shiro 类似,一般用于用户认证(Authentication)和用户授权(Authorization)两个部分,常与与SpringBoot相整合。

1. Security基本使用

1.1 安装

Eureka服务端和客户端都需要安装
maven方式安装

  1. <!-- Security -->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-security</artifactId>
  5. </dependency>

gradle方式安装

  1. //开启Security
  2. implementation 'org.springframework.boot:spring-boot-starter-security'

1.2 Eureka服务端增加配置

  1. #安全认证
  2. spring.security.user.name=wangfan
  3. spring.security.user.password=123

1.3 启动类增加注解 @``EnableWebSecurity

  1. @EnableEurekaServer
  2. @SpringBootApplication
  3. @EnableWebSecurity
  4. public class EurekaApplication {
  5. public static void main(String[] args) {
  6. SpringApplication.run(EurekaApplication.class, args);
  7. }
  8. }

1.4 Eureka客户端修改配置

修改前

  1. #设置服务注册中心的URL
  2. eureka.client.service-url.defaultZone=http://localhost:8080/eureka/

修改后

  1. #设置服务注册中心的URL
  2. eureka.client.service-url.defaultZone=http://wangfan:123@localhost:8080/eureka/

如果服务注册报错

Root name ‘timestamp’ does not match expected (‘instance’) for type [simple

是默认开启了防止csrf攻击, 则需手动关闭csrf防御.
在Eureka服务端增加配置类即可

  1. import org.springframework.context.annotation.Configuration;
  2. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  3. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  4. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  5. /**
  6. * @Author:壹心科技BCF项目组 wangfan
  7. * @Date:Created in 2020/10/5 00:59
  8. * @Project:epec
  9. * @Description:关闭XSS防御
  10. * @Modified By:wangfan
  11. * @Version: V1.0
  12. */
  13. @Configuration
  14. @EnableWebSecurity
  15. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  16. @Override
  17. protected void configure(HttpSecurity http) throws Exception {
  18. //关闭csrf防御
  19. http.csrf().disable();
  20. super.configure(http);
  21. }
  22. }