web-security第二期:Spring Security 框架概览

本文深入剖析Spring Security框架的核心组件,包括FilterChain、DelegatingFilterProxy、FilterChainProxy、SecurityFilterChain等,揭示其工作原理及异常处理机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

阅读本文之前,我默认您已经掌握 spring-web spring-boot 的基础知识

本文的编写依据是  Spring Security 官方文档

Spring Security 是一个安全框架,前身是 Acegi Security,能够为 Spring 企业应用系统提供声明式的安全访问控制。Spring Security 基于 Servlet 过滤器、IoC 和 AOP,为 Web 请求和方法调用提供身份确认和授权处理,避免了代码耦合,减少了大量重复代码工作。

既然Spring Security是基于Filter来实现的,那咱们先从Filter 开始:

1.FilterChain

Filter是在Servlet容器启动前被注册,如下:这是一个典型的过滤链,通过(chain.doFilter(request, response))一层层的过滤请求

filterchain

2.DelegatingFilterProxy

Servlet容器允许使用其自己的标准注册Filters,但它不了解Spring定义的Bean,而DelegatingFilterProxy 在Servlet容器和Spring的ApplicationContext之间搭建了一个桥梁。使得Servlet可以注册在SpringApplicationContext中定义的Filter,如下图所示

delegatingfilterproxy

DelegatingFilterProxy从ApplicationContext查找Bean Filter0,然后调用Bean Filter0。 伪代码如下:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
    // Lazily get Filter that was registered as a Spring Bean
    // For the example in DelegatingFilterProxy delegate is an instance of Bean Filter0
    Filter delegate = getFilterBean(someBeanName);
    // delegate work to the Spring Bean
    delegate.doFilter(request, response);
}

DelegatingFilter还有一个好处:延迟注册Filter Bean

在 spring-web第一期 我曾分析过,因为Servlet容器需要在容器启动之前注册Filter实例。但是,Spring通常使用ContextLoaderListener加载Spring Bean,因此在容器启动前是不可以获取Spring Bean的,直到Spring容器启动后才可以注册这些Filter。

 

3. FilterChainProxy

Spring Security的对Servlet的支持包含在FilterChainProxy中。 FilterChainProxy是Spring Security提供的特殊过滤器,允许通过SecurityFilterChain委派许多过滤器实例。由于FilterChainProxy是一个Bean,因此通常将其包装在DelegatingFilterProxy中。

filterchainproxy

4. SecurityFilterChain

FilterChainProxy使用SecurityFilterChain确定应对此请求调用哪些Spring Security过滤器

securityfilterchain

SecurityFilterChain中的Security FIlter 通常是Bean,但它们使用的是FilterChainProxy而不是DelegatingFilterProxy注册的。 FilterChainProxy具有直接向Servlet容器或DelegatingFilterProxy注册的许多优点。例如,它为Spring Security的所有Servlet支持提供了一个起点。因此,如果您想对Spring Security的Servlet支持进行BUG排除,那么在FilterChainProxy中添加调试点是一个很好的选择。

实际上,FilterChainProxy 甚至可以确定来使用哪一个 SecurityFilterChain, 前提是你可以为你的应用程序提供多个完全独立的配置空间,如下图所示:

multi securityfilterchain

FilterChainProxy决定应使用哪个SecurityFilterChain(每个FilterChain中拥有的Filter个数可不相同)。仅匹配的第一个SecurityFilterChain将被调用。如果请求的URL是/ api / messages /,则它将首先与SecurityFilterChain0的/ api / **模式匹配,因此,即使SecurityFilterChain0也与SecurityFilterChainn匹配,也只会调用它。假设都没有匹配上,那么默认使用 SecurityFilterChain n (即最后一个)

5.SecurityFilters的顺序

SecurityFilters 通过SecurityFilterChain API插入到FilterChainProxy中。过滤器的顺序很重要。虽然通常不必要知道Spring Security的过滤器的顺序。但是,有时候了解还是有好处的,如下是Security Filters的完整列表:(蓝色部分是较为重要的过滤器)

  • ChannelProcessingFilter

  • ConcurrentSessionFilter

  • WebAsyncManagerIntegrationFilter

  • SecurityContextPersistenceFilter

  • HeaderWriterFilter

  • CorsFilter

  • CsrfFilter

  • LogoutFilter

  • OAuth2AuthorizationRequestRedirectFilter

  • Saml2WebSsoAuthenticationRequestFilter

  • X509AuthenticationFilter

  • AbstractPreAuthenticatedProcessingFilter

  • CasAuthenticationFilter

  • OAuth2LoginAuthenticationFilter

  • Saml2WebSsoAuthenticationFilter

  • UsernamePasswordAuthenticationFilter

  • ConcurrentSessionFilter

  • OpenIDAuthenticationFilter

  • DefaultLoginPageGeneratingFilter

  • DefaultLogoutPageGeneratingFilter

  • DigestAuthenticationFilter

  • BearerTokenAuthenticationFilter

  • BasicAuthenticationFilter

  • RequestCacheAwareFilter

  • SecurityContextHolderAwareRequestFilter

  • JaasApiIntegrationFilter

  • RememberMeAuthenticationFilter

  • AnonymousAuthenticationFilter

  • OAuth2AuthorizationCodeGrantFilter

  • SessionManagementFilter

  • ExceptionTranslationFilter

  • FilterSecurityInterceptor

  • SwitchUserFilter

6. Handling Security Exceptions

既然过滤链这么多,那么如果在哪一个环节碰到异常该怎么抛出了,最理想的办法当然是将异常以可阅读,可定位的方式反馈给客户端(如使用HTTP返回)

我们先来说说异常,Spring Security 中最常见的两个异常是:

  • AccessDeniedException (拒绝访问异常)
  • AuthenticationException (认证异常)

exceptiontranslationfilter

 

  • number 1 正常执行过滤链,如果发生异常,则判断是什么类型的异常

  •  number 2 如果是AuthenticationException,则对用户进行认证授权,步骤如下

    • 清除 SecurityContextHolder

    • 将请求放入 RequestCache 中进行缓存,如果用户认证通过,则从这里重发此请求

    • AuthenticationEntryPoint用于从客户端请求凭据

  • number 3 如果它是AccessDeniedException,则拒绝访问。并调用AccessDeniedHandler处理拒绝的访问

注:如果应用程序未引发AccessDeniedException或AuthenticationException,则ExceptionTranslationFilter不执行任何操作。

伪代码如下:

try {
    filterChain.doFilter(request, response); 
} catch (AccessDeniedException | AuthenticationException e) {
    if (!authenticated || e instanceof AuthenticationException) {
        startAuthentication(); 
    } else {
        accessDenied(); 
    }
}

 

03-20
<think>好的,用户现在问的是关于LPCTSTR的问题。首先,我需要回忆一下这个类型在Windows编程中的用途定义。LPCTSTR是一个指向常量TCHAR字符串的指针,通常用于处理不同字符编码的情况,比如在UnicodeANSI编码之间切换。 用户之前的问题是关于按钮文本中文乱码的,现在转向LPCTSTR,可能是因为在解决乱码问题时遇到了这个类型,需要更深入的理解。所以需要解释清楚LPCTSTR的结构、用途以及在不同环境下的表现。 首先,我应该先定义LPCTSTR,然后分解每个字母的含义:L表示long pointer,P表示指针,C表示const,TSTR表示TCHAR字符串。然后说明TCHAR的作用,它是为了支持多编码而定义的宏,根据是否定义了UNICODE宏,TCHAR会变成char或wchar_t。 接下来,要举一些例子,比如在Unicode非Unicode环境下LPCTSTR的实际类型是什么,这样用户能更直观地理解。例如,当使用Unicode时,LPCTSTR实际上是const wchar_t*,否则是const char*。 然后,需要说明LPCTSTR的常见使用场景,比如在Windows API函数中的参数传递,特别是那些需要字符串参数的地方,比如CreateWindowEx、MessageBox等。这里可以举一个MessageBox的例子,展示如何使用LPCTSTR。 另外,用户可能在使用LPCTSTR时遇到编译错误或者转换问题,尤其是在混合使用不同字符集的情况下。所以需要提到相关的宏定义,比如_UNICODEUNICODE,以及如何使用_T()或TEXT()宏来确保字符串字面量的正确类型。 还要注意常见的问题,比如类型转换错误,比如将LPCTSTR误转换为其他类型,或者在不同编码项目中的兼容性问题。给出解决方案,比如检查项目属性中的字符集设置,使用合适的宏转换函数,如MultiByteToWideCharWideCharToMultiByte。 最后,总结LPCTSTR的重要性,强调在Windows编程中正确处理字符串类型对于避免乱码兼容性问题的重要性,并建议始终使用Unicode字符集以提高兼容性。 需要确保回答结构清晰,分点说明,并给出示例代码,这样用户能够逐步理解应用。同时要避免使用过于专业的术语,保持解释的易懂性,特别是考虑到用户可能是在学习或解决实际问题中遇到这个概念。</think>以下是关于 Windows 编程中 `LPCTSTR` 类型的详细解析: --- ### 一、基础定义 `LPCTSTR` 是 **Windows API 核心字符串类型**,其结构分解为: - **L**:长指针 (Long Pointer,历史遗留命名) - **P**:指针 (Pointer) - **C**:常量 (Const) - **TSTR**:`TCHAR` 字符串 (T-character String) 本质上是为兼容 **ANSI/Unicode 双模式**设计的通用字符串指针类型。 --- ### 二、类型映射关系 实际数据类型根据编译环境动态变化: | 编译模式 | `TCHAR` 定义 | `LPCTSTR` 等效类型 | 字符宽度 | |---------------|-------------|------------------------|--------| | **ANSI 模式** | `char` | `const char*` | 1字节 | | **Unicode 模式**| `wchar_t` | `const wchar_t*` | 2字节 | **模式切换条件**: 通过预定义宏 `UNICODE` `_UNICODE` 控制(需在项目属性或代码头部定义)。 --- ### 三、核心应用场景 #### 1. Windows API 参数传递 ```cpp // 创建窗口示例 HWND hWnd = CreateWindowEx( 0, // 扩展样式 _T("MyWindowClass"), // LPCTSTR 类名 _T("窗口标题"), // LPCTSTR 标题 WS_OVERLAPPEDWINDOW, // 窗口样式 CW_USEDEFAULT, CW_USEDEFAULT, // 位置 500, 300, // 尺寸 NULL, NULL, hInstance, NULL ); ``` #### 2. 资源字符串处理 ```cpp // 加载字符串资源 LPCTSTR str = LoadString(hInstance, IDS_HELLO, NULL, 0); ``` #### 3. 消息处理 ```cpp // 消息框示例 MessageBox(NULL, _T("文件保存成功!"), // LPCTSTR 内容 _T("提示"), // LPCTSTR 标题 MB_OK); ``` --- ### 四、字符串字面量处理技巧 使用 `_T()` 或 `TEXT()` 宏保证兼容性: ```cpp // 正确写法 LPCTSTR str1 = _T("中文文本"); LPCTSTR str2 = TEXT("多语言支持"); // 错误写法(可能导致编码问题) LPCTSTR str3 = "Non-unicode text"; // 在Unicode模式下会编译失败 ``` --- ### 五、类型转换对照表 | 转换方向 | API函数 | 示例 | |----------------------|---------------------------|-----------------------------| | `LPCTSTR` → `LPCWSTR` | 无需转换(Unicode模式下等效) | `LPCWSTR wideStr = lpctStr;` | | `LPCTSTR` → `LPCSTR` | `WideCharToMultiByte` | 需处理字符编码转换 | | `LPCSTR` → `LPCTSTR` | `MultiByteToWideChar` | 需指定代码页(如 CP_ACP) | --- ### 六、常见问题排查 #### 1. 编译错误 C2440 **现象**:`cannot convert from 'const char [6]' to 'LPCTSTR'` **原因**:项目设置为Unicode模式但使用ANSI字符串 **解决**:使用 `_T("text")` 包裹字符串 #### 2. 乱码显示 **场景**:Unicode程序在ANSI终端输出 **方案**:统一编码体系或使用转换函数: ```cpp // Unicode转ANSI示例 char buffer[256]; WideCharToMultiByte(CP_ACP, 0, lpctStr, -1, buffer, 256, NULL, NULL); ``` #### 3. 内存访问违规 **典型情况**:错误类型转换导致指针越界 **防御措施**:使用安全函数: ```cpp #include <strsafe.h> StringCchCopy(lpDestStr, destSize, lpctSrcStr); ``` --- ### 七、现代编程建议 1. **优先使用Unicode模式**:所有现代Windows系统均原生支持Unicode 2. **弃用TCHAR体系**:新项目建议直接使用 `wchar_t` `L""` 字面量 3. **跨平台兼容**:如需跨平台开发,推荐使用 `std::wstring` (Windows) `std::string` (其他平台) --- 通过理解 `LPCTSTR` 的双模式特性,开发者可以更好地处理 Windows 程序中的多语言支持问题,避免90%以上的字符编码相关错误。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值