使用Spring Security,我如何使用HTTP方法(例如GET,PUT,POST)来distingush特定URL模式的安全性?

2022-09-02 19:19:54

Spring Security 参考指出:

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

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


答案 1

这只是关于配置。它说这些元素将在配置文件的标记中从上到下进行评估:<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>

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


答案 2

对于那些喜欢基于 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>

推荐