【Spring】Spring Security 5及以上版本中`SecurityFilterChain`示例

1. 配置SecurityFilterChain

在Spring Boot应用程序中,通常通过配置类来定义SecurityFilterChain。Spring Boot 2.x及更高版本与Spring Security 5.x紧密集成,提供了简化的配置方式。以下是一个基于Java配置的例子:

import org.springframework.context.annotation.Bean;  
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.web.SecurityFilterChain;  
  
@Configuration  
@EnableWebSecurity  
public class SecurityConfig {  
  
    @Bean  
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {  
        http  
            // 配置哪些请求需要认证  
            .authorizeRequests()  
                .antMatchers("/public/**").permitAll() // 公开路径不需要认证  
                .anyRequest().authenticated() // 其他路径都需要认证  
            .and()  
            // 配置表单登录  
            .formLogin()  
                .loginPage("/login") // 自定义登录页面  
                .loginProcessingUrl("/perform_login") // 自定义登录处理URL  
                .defaultSuccessUrl("/home", true) // 登录成功后跳转到的页面  
            .and()  
            // 配置注销  
            .logout()  
                .logoutUrl("/logout") // 注销URL  
                .logoutSuccessUrl("/login?logout") // 注销成功后跳转到的页面  
            .and()  
            // 其他安全配置...  
            ;  
  
        // 返回一个配置好的SecurityFilterChain实例  
        return http.build();  
    }  
}

2.SecurityFilterChain的工作原理

  • 当一个HTTP请求到达Spring应用程序时,FilterChainProxy(Spring Security的一个组件)会拦截该请求。
  • FilterChainProxy会根据请求的路径和配置的SecurityFilterChain来决定将请求转发给哪个SecurityFilterChain实例。
  • 选定的SecurityFilterChain中的过滤器将按顺序执行,每个过滤器都会根据其职责对请求进行处理。
  • 如果请求在某个过滤器中被认为是合法的,则它将继续传递到下一个过滤器,直到达到最终的目的地(如控制器)。
  • 如果请求在某个过滤器中被拦截(如认证失败),则过滤器会返回一个响应,并且请求将不再继续传递。

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值