Spring Security简介
Spring Security 是专门针对基于Spring的项目安全框架,充分利用了依赖注入和AOP来实现安全的功能,安全框架主要用的是认证(Authentication)和授权(Authorization)。
SpringBoot 对其的支持
关于Spring Security 的自动配置在SpringBoot 中在org.springframework.boot.autoconfigure.security包中
关于在SpringBoot中配置Spring Security 包含下图这样
当我们需要使用自己的扩展配置时需要自己的类实现WebSecurityConfigurerAdapter类即可
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
UserDetailsService customUserService(){
return new CustomUserService();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserService());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.permitAll()
.and()
.logout()
.permitAll();
}
}
实战
- 首先添加pom文件 。这里使用的mysql 数据库
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-