Spring Security 教程(18)、开始使用安全命名空间配置

最简单的安全配置

namespace-usage 配图
namespace-usage 配图
namespace-usage 配图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
https://www.springframework.org/schema/security/spring-security.xsd">

<http auto-config="true">
<intercept-url pattern="/public/**" access="permitAll()"/>
<intercept-url pattern="/admin/**" access="hasRole('ADMIN')"/>
<intercept-url pattern="/**" access="authenticated()"/>
</http>

<authentication-manager>
<authentication-provider>
<user-service>
<user name="admin" password="{bcrypt}$2a$10$..." authorities="ROLE_ADMIN"/>
</user-service>
</authentication-provider>
</authentication-manager>

</beans:beans>

关键配置元素解析

<http auto-config="true">:启用默认安全配置,包括表单登录、退出、remember-me 等。

<intercept-url>:定义 URL 模式和安全规则。可以配置多个,按顺序匹配。

access 属性:指定访问规则,支持 SpEL 表达式:

  • permitAll():允许所有
  • authenticated():需要认证
  • hasRole('ADMIN'):需要 ADMIN 角色
  • isAuthenticated():等同于 authenticated()
  • fullyAuthenticated():需要完全认证(非 remember-me)

表单登录配置

1
2
3
4
5
6
7
<http>
<form-login login-page="/login"
authentication-failure-url="/login?error"
default-target-url="/dashboard"
username-parameter="username"
password-parameter="password"/>
</http>

CSRF 配置

1
2
3
4
5
<http>
<csrf disabled="true"/>
<!-- 或者自定义 CSRF 配置 -->
<csrf csrf-token-request-handler="csrfTokenRequestHandler"/>
</http>

认证提供者配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<authentication-manager>
<!-- 内存认证 -->
<authentication-provider>
<user-service>
<user name="user" password="{bcrypt}..." authorities="ROLE_USER"/>
</user-service>
</authentication-provider>

<!-- JDBC 认证 -->
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query="select username, password, enabled from users where username=?"
authorities-by-username-query="select username, authority from authorities where username=?"/>
</authentication-provider>

<!-- LDAP 认证 -->
<authentication-provider>
<ldap-authentication-provider
server-url="ldap://ldap.example.com:389"
manager-dn="cn=admin,dc=example,dc=com"
manager-password="adminpwd"/>
</authentication-provider>
</authentication-manager>

何时从 XML 迁移到 Java Config

当你的安全配置开始变得复杂(需要条件化逻辑、动态配置、多环境适配)时,XML 命名空间会显得力不从心。这时应该迁移到 Java Config。迁移时遵循”等价替换”原则:每个 XML 元素都有对应的 Java API。