SpringSecurity是Spring下的一个安全框架,与shiro 类似,一般用于用户认证(Authentication)和用户授权(Authorization)两个部分,常与与SpringBoot相整合。
1. Security基本使用
1.1 安装
Eureka服务端和客户端都需要安装
maven方式安装
<!-- Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
gradle方式安装
//开启Security
implementation 'org.springframework.boot:spring-boot-starter-security'
1.2 Eureka服务端增加配置
#安全认证
spring.security.user.name=wangfan
spring.security.user.password=123
1.3 启动类增加注解 @``EnableWebSecurity
@EnableEurekaServer
@SpringBootApplication
@EnableWebSecurity
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class, args);
}
}
1.4 Eureka客户端修改配置
修改前
#设置服务注册中心的URL
eureka.client.service-url.defaultZone=http://localhost:8080/eureka/
修改后
#设置服务注册中心的URL
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服务端增加配置类即可
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.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
* @Author:壹心科技BCF项目组 wangfan
* @Date:Created in 2020/10/5 00:59
* @Project:epec
* @Description:关闭XSS防御
* @Modified By:wangfan
* @Version: V1.0
*/
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//关闭csrf防御
http.csrf().disable();
super.configure(http);
}
}