2011-09-08 140 views
12

Spring Security的參考狀態:使用Spring Security,如何使用HTTP方法(例如GET,PUT,POST)爲特定URL模式的distingush安全性?

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

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

回答

25

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

4

對於那些喜歡基於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的安全也應工作):

<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> 
相關問題