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

Java 使用Spring安全性,我如何使用HTTP方法(例如GET、PUT、POST)来区分特定URL模式的安全性?,java,spring,spring-security,http-method,Java,Spring,Spring Security,Http Method,Spring安全参考说明: 可以使用多个元素来定义不同的 不同URL集的访问要求,但它们将是 按列出的顺序计算,将使用第一个匹配项。那么你呢 必须将最具体的匹配项放在顶部。您还可以添加 方法属性将匹配限制为特定HTTP方法(GET, 邮寄、邮寄等)。如果一个请求匹配多个模式,则 无论顺序如何,方法特定的匹配将优先 如何配置Spring安全性,以便根据用于访问URL模式的HTTP方法对特定URL模式的访问进行不同的安全保护?这只是关于配置。它表示将在配置文件的标记中从上到下评估元素: <ht

Spring安全参考说明:

可以使用多个元素来定义不同的 不同URL集的访问要求,但它们将是 按列出的顺序计算,将使用第一个匹配项。那么你呢 必须将最具体的匹配项放在顶部。您还可以添加 方法属性将匹配限制为特定HTTP方法(GET, 邮寄、邮寄等)。如果一个请求匹配多个模式,则 无论顺序如何,方法特定的匹配将优先


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

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

<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访问
/client/edit
,用户只需要经过身份验证,但要通过POST访问
/client/edit
(比如,提交编辑表单),用户需要具有
编辑器
角色。这种url模式在某些地方可能不受鼓励,但它只是一个示例。

对于那些喜欢基于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的早期版本也可以使用):


org.springframework.security
spring安全网
5.0.0.M3
org.springframework.security
spring安全配置
5.0.0.M3

mvcMatchers也是如此,它是在Spring Security 4.1.1中添加的,被认为更安全。
    <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>