Spring Security 多过滤链的使用详解
一、背景
在我们实际的开发过程中,有些时候可能存在这么一些情况,某些api 比如: /api
@Configuration
public class AppSecurityConfig {
@Bean
@Order(1)
public SecurityFilterChain appSecurityFilterChain(HttpSecurity http) throws Exception {
// 只处理 /api 开头的请求
return http.antMatcher("/api
@Configuration
public class WebSiteSecurityFilterChainConfig {
@Bean
@Order(2)
public SecurityFilterChain webSiteSecurityFilterChain(HttpSecurity http) throws Exception {
AuthenticationManagerBuilder authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class);
// 创建用户
authenticationManagerBuilder.inMemoryAuthentication()
.withUser("admin")
.password(new BCryptPasswordEncoder().encode("admin"))
.authorities(AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_ADMIN"))
.and()
.withUser("dev")
.password(new BCryptPasswordEncoder().encode("dev"))
.authorities(AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_DEV"))
.and()
.passwordEncoder(new BCryptPasswordEncoder());
// 只处理 所有 开头的请求
return http.antMatcher("
@Bean
public WebSecurityCustomizer webSecurityCustomizer( ){
return web -> web.ignoring()
.antMatchers("jscss
@Controller
public class ResourceController {
@GetMapping("/api/userInfo")
@ResponseBody
public Authentication showUserInfoApi() {
return SecurityContextHolder.getContext().getAuthentication();
}
@GetMapping("/index")
public String index(Model model){
model.addAttribute("username","张三");
return "index";
}
}
4、引入jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
五、实现效果
1、app 有权限访问 api
2、app 无权限访问 api
3、admin 用户有权限访问 网站 api
4、dev 用户无权限访问 网站 api
访问无权限的API直接跳转到 百度 首页。
六、完整代码
https://gitee.com/huan1993/Spring-Security/tree/master/multi-security-filter-chain
到此这篇关于Spring Security 多过滤链的使用详解的文章就介绍到这了,更多相关Spring Security 多过滤链 内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!