簡體   English   中英

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

[英]Using Spring Security, how can I use HTTP methods (e.g. GET, PUT, POST) to distingush security for particular URL patterns?

Spring Security參考說明:

您可以使用多個元素為不同的URL集定義不同的訪問要求,但它們將按列出的順序進行評估,並將使用第一個匹配項。 所以你必須把最具體的比賽放在最上面。 您還可以添加方法屬性以限制與特定HTTP方法(GET,POST,PUT等)的匹配。 如果請求與多個模式匹配,則無論排序如何,特定於方法的匹配都將優先。

如何配置Spring Security,以便根據用於訪問URL模式的HTTP方法,以不同方式保護對特定URL模式的訪問?

這只是關於配置。 它表示<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訪問/client/edit ,用戶只需要進行身份驗證,但要通過POST訪問/client/edit (比如提交編輯表單),用戶需要具有EDITOR角色。 在某些地方可能不鼓勵這種網址模式,但這只是一個例子。

對於那些更喜歡基於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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM