需通过security.xml配置Spring Security:启用命名空间并配置http与authentication-manager;设置URL权限映射;集成自定义UserDetailsService;按需禁用CSRF;启用remember-me功能。

如果您正在维护一个基于旧版Spring框架的应用程序,且需要使用XML方式配置Spring Security功能,则需通过security.xml文件定义认证、授权、HTTP安全约束等核心行为。以下是实现该配置的常用方法:
一、启用Spring Security命名空间并声明基础配置
Spring Security 3.0+支持基于XML命名空间的简化配置,需在security.xml中引入对应命名空间,并配置<http>与<authentication-manager>两大核心元素,以启用Web安全拦截和用户认证管理。
1、在security.xml根元素中添加命名空间声明:xmlns:security="http://www.springframework.org/schema/security",并在xsi:schemaLocation中补充对应XSD地址。
2、添加<security:http auto-config="true">元素,启用默认登录页、CSRF防护(Spring Security 4.0+默认开启)、会话管理及基本访问控制。
3、配置内存认证提供者:
<security:authentication-manager><br>
<security:authentication-provider><br>
<security:user-service><br>
<security:user name="admin" password="{noop}password123" authorities="ROLE_ADMIN"/><br>
</security:user-service><br>
</security:authentication-provider><br>
</security:authentication-manager>
4、确保web.xml中已注册DelegatingFilterProxy,过滤器名称必须为springSecurityFilterChain,否则配置不生效。
二、配置受保护URL路径与角色权限映射
通过<security:intercept-url>子元素可精确指定不同URL模式所需的访问权限,Spring Security将按声明顺序匹配,优先采用首个匹配项。
1、在<security:http>内添加路径拦截规则:<security:intercept-url pattern="/admin/**" access="ROLE_ADMIN"/>
2、为公共资源放行,避免被拦截:<security:intercept-url pattern="/resources/**" security="none"/>(Spring Security 3.x)或<security:intercept-url pattern="/resources/**" permitAll="true"/>(Spring Security 4.x+)。
3、配置登录与登出端点:<security:form-login login-page="/login" default-target-url="/home" authentication-failure-url="/login?error"/>
4、注意:pattern属性值必须使用Ant风格路径,且/开头;access属性值中多个角色用逗号分隔,如"ROLE_USER,ROLE_EDITOR"
三、集成自定义UserDetailsService实现类
当用户信息存储于数据库或外部系统时,需替换默认内存认证,改用自定义服务类加载用户凭证与权限,确保认证逻辑与业务数据一致。
1、编写实现org.springframework.security.core.userdetails.UserDetailsService接口的类,例如CustomUserDetailsService。
2、在security.xml中声明该Bean:<bean id="userDetailsService" class="com.example.security.CustomUserDetailsService"/>
3、在<security:authentication-provider>中引用:
<security:authentication-provider user-service-ref="userDetailsService"><br> <security:password-encoder ref="passwordEncoder"/><br> </security:authentication-provider>
4、必须同时配置密码编码器(如BCryptPasswordEncoder),否则明文密码比对将失败
四、禁用CSRF防护(仅限特定场景)
在Spring Security 4.0及以上版本中,CSRF防护默认启用,若应用为纯REST API且无会话状态,或前端未携带CSRF Token,则需显式关闭,否则POST/PUT/DELETE请求将返回403错误。
1、在<security:http>内添加子元素:<security:csrf disabled="true"/>
2、确认所有表单提交与AJAX请求不再依赖_csrf参数或Header。
3、禁用CSRF后,系统将失去对跨站请求伪造攻击的基础防护,仅应在无会话、无敏感操作的API场景下使用
五、配置Remember-Me自动登录功能
通过remember-me机制,可在用户勾选“记住我”后生成持久化令牌,使浏览器在会话过期后仍能自动完成认证,提升用户体验。
1、在<security:http>内添加:<security:remember-me key="myAppKey" token-validity-seconds="86400"/>
2、若使用数据库存储令牌,需配置JdbcTokenRepositoryImpl:
<bean id="tokenRepository" class="org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl"><br> <property name="dataSource" ref="dataSource"/><br> </bean>
3、在<security:remember-me>中添加token-repository-ref="tokenRepository"属性。
4、remember-me密钥(key属性)必须全局唯一且保密,泄露将导致任意用户伪造登录凭证










