4.1SpringBoot集成Spring Security
4.1.1SpringBoot介绍
略。
4.1.2创建SprngBoot工程
引入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- spring security start -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>2.3.0.RELEASE</version>
</dependency>
<!-- spring security end -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.6.2</version>
</dependency>
创建springboot配置类:
@Configuration
public class MyConfig implements WebMvcConfigurer {
@Bean
public WebMvcConfigurer webMvcConfigurer(){
WebMvcConfigurer webMvcConfigurer = new WebMvcConfigurer() {
//视图映射器
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("redirect:/login");
}
};
return webMvcConfigurer;
}
}
创建spring Security配置类:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
protected UserDetailsService userDetailsService() {
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(User.withUsername("zhangsan").password("123").authorities("p1").build());
manager.createUser(User.withUsername("lisi").password("456").authorities("p2").build());
return manager;
}
//安全配置
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeHttpRequests()
.antMatchers("/r/r1").hasAuthority("p1")
.antMatchers("/r/r2").hasAuthority("p2")
.antMatchers("/r/**").authenticated()
.and().formLogin()
.successForwardUrl("/loginSuccess");
}
@Bean
public PasswordEncoder passwordEncoder(){
return NoOpPasswordEncoder.getInstance();
}
}
4.2工作原理
4.2.1结构总览
Spring Security解决的问题就是安全访问控制,而安全访问控制功能其实就是对所有进入系统的请求进行拦截,校验每个请求是否能够访问他所期望的资源。可以通过Filter和AOP等技术来实现,Spring Security对Web资源的保护是靠Filter来实现的。
当初始化Spring Security时,会创建一个名为SpringSecurityFilterChain的过滤器,类型为
org.springframework.security.web.FilterChainProxy
它继承了GenericFilterBean,GenericFilterBean实现了Filter,因此外部的请求会经过此类:
下图为过滤器链路结构图: