18

Spring Security 参考说明:

您可以使用多个元素为不同的 URL 集定义不同的访问要求,但它们将按列出的顺序进行评估,并且将使用第一个匹配项。因此,您必须将最具体的匹配项放在顶部。您还可以添加方法属性以将匹配限制为特定的 HTTP 方法(GET、POST、PUT 等)。如果一个请求匹配多个模式,则无论排序如何,特定于方法的匹配都将优先。

如何配置 Spring Security,以便根据用于访问 URL 模式的 HTTP 方法对特定 URL 模式的访问进行不同的保护?

4

2 回答 2

28

这只是关于配置。它表示将在配置文件的标记中<intercept-url>从上到下评估元素:<http />

<http auto-config="true">
    <intercept-url pattern="/**" access="isAuthenticated" />
    <intercept-url pattern="/login.jsp" access="permitAll" />
</http>

在上面的示例中,我们试图只允许经过身份验证的用户访问所有内容,当然登录页面除外(用户必须先登录,对吗?!)。但是,根据文档,这不起作用,因为不太具体的匹配在顶部。因此,完成此示例目标的(其中一个)正确配置是:

<http auto-config="true">
    <intercept-url pattern="/login.jsp" access="permitAll" />
    <intercept-url pattern="/**" access="isAuthenticated" />
</http>

将更具体的匹配放在顶部。

引用的最后一件事是关于 HTTP 方法。您可以使用它来指定匹配项,因此:

<http auto-config="true">
    <intercept-url pattern="/client/edit" access="isAuthenticated" method="GET" />
    <intercept-url pattern="/client/edit" access="hasRole('EDITOR')" method="POST" />
</http>

在第二个示例中,要/client/edit通过 GET 访问用户只需要经过身份验证,但要/client/edit通过 POST 访问(比如说,提交编辑表单),用户需要具有EDITOR角色。在某些地方可能不鼓励使用这种 url 模式,但这只是一个示例。

于 2011-09-09T13:12:51.413 回答
26

对于那些喜欢基于 Java 注释的配置的用户,请将此类放入您的应用程序中。

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers(HttpMethod.GET).permitAll();
        http.authorizeRequests().antMatchers(HttpMethod.POST).denyAll();
        http.authorizeRequests().antMatchers(HttpMethod.DELETE,"/you/can/alsoSpecifyAPath").denyAll();
        http.authorizeRequests().antMatchers(HttpMethod.PATCH,"/path/is/Case/Insensitive").denyAll();
        http.authorizeRequests().antMatchers(HttpMethod.PUT,"/and/can/haveWildcards/*").denyAll();

    }

}

使用以下 Maven 依赖项(早期版本的 Spring-Security 也应该可以工作):

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>5.0.0.M3</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>5.0.0.M3</version>
    </dependency>
于 2017-08-30T16:13:19.673 回答