如何在没有身份验证的情况下允许GET请求但是保护其他HTTP方法?

时间:2015-06-04 12:32:39

标签: java spring spring-security roo

我创建了一个带有spring roo的web服务,并为项目增加了弹簧安全性。到目前为止一切正常但现在我想允许通过HTTP GET请求访问实体信息而无需任何身份验证。其他HTTP方法如POST,PUT等应保持安全。

我的applicationContext-security.xml如下所示,但当我在" / releaseupdates /"上进行HTTP GET时;用"接受:application / json"标题它总是返回登录页面(我认为spring security会在内部重定向到登录页面):

 <http auto-config="true" use-expressions="true">
        <form-login login-processing-url="/resources/j_spring_security_check" login-page="/login" authentication-failure-url="/login?login_error=t" />
        <logout logout-url="/resources/j_spring_security_logout" />
        <!-- Configure these elements to secure URIs in your application -->
        <intercept-url pattern="/releaseupdates/**" access="permitAll" method="GET" />
        <intercept-url pattern="/releaseupdates/**" access="hasRole('ROLE_ADMIN')" method="POST" />
        <intercept-url pattern="/releaseupdatestatuses/**" access="hasRole('ROLE_ADMIN')"/>
        <intercept-url pattern="/choices/**" access="hasRole('ROLE_ADMIN')" />
        <intercept-url pattern="/member/**" access="isAuthenticated()" />
        <intercept-url pattern="/resources/**" access="permitAll" />
        <intercept-url pattern="/login/**" access="permitAll" />
        <intercept-url pattern="/**" access="isAuthenticated()" />
</http>

1 个答案:

答案 0 :(得分:2)

还有一个注释@PreAuthorize,它可能是你的朋友。注释可以是控制器上的类或方法级别。

以下是一个例子:

@Controller
@RequestMapping("/releaseupdates")
public class ReleaseUpdateController {

   @RequestMapping(method=RequestMethod.GET)
   public String unprotectedGetRequest() {
      //do something, no protection
   }

   @PreAuthorize("hasRole('ROLE_ADMIN')")
   @RequestMapping(method=RequestMethod.POST)
   public String securePostRequest() {
      //do something, secured
   }

}