2014-01-29 122 views
0

我正在試圖爲我的Spring應用程序實現一個REST API。由於有些資源可能無法被每個人訪問,我需要一個安全層。用Spring Security保護REST API

在我已經使用Spring安全(這工作完全正常)爲確保我的web應用程序這個應用程序。

我已經添加了以下http配置到我的spring-security.xml

<http pattern = "/api/**" use-expressions = "true" disable-url-rewriting = "true"> 
    <http-basic /> 
</http> 

所以我認爲這是開始api/網址的所有請求將被保護。

問題是,我可以訪問我的固定方法沒有任何認證。但是,如果使用REST客戶端來訪問它,我收到此錯誤:

message: Full authentication is required to access this resource 
description: This request requires HTTP authentication. 

我不知道如何着手。使用Spring Security來保護REST API的最佳方式是什麼?

+0

如何訪問您的安全方法,你說你看到他們沒有身份驗證?通過瀏覽器?您是否已登錄瀏覽器並登錄了用戶? – nobeh

回答

1

如果您在應用程序中使用Spring Security,你,也許已經在你的Spring配置文件之一的<http>部分。您可以使用此部分來保護您的REST API。

<http>不保證其自身的東西。您必須在其中添加<intercept-url>規則:

<intercept-url pattern="/api/**" access="hasRole('ROLE_USER')" /> 
+0

但我在我的控制器中使用@PreAuthorize。所以我認爲我不需要它。我沒有在其他'http'部分使用..無論如何,問題是,通過瀏覽器驗證工作正常,但不是與我的REST客戶端。 – mhmpl

0

在Spring的官方網站上有一個tuto。它有點複雜: Official Spring Tuto

+0

我不使用JavaConfig,另外我有兩個安全上下文(webapp和rest api)。 – mhmpl

0

只要使用Spring Security。<http>標籤添加:<security:intercept-url pattern="your url" access="hasAnyRole('Your_User_Role1', 'Your_User_Role2')" />
或者嘗試使用註釋。在Spring-config.xml中啓用安全註釋:
<security:global-method-security jsr250-annotations="enabled" pre-post-annotations="enabled" secured-annotations="enabled"/> 和控制器添加@PreAuthorize

@PreAuthorize("hasAnyRole('Your_User_Role1', 'Your_User_Role2')") 
@RequestMapping(value = "/address_planing/load_employee_info")