2014-01-29 123 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")