2013-11-01 51 views
5

我有一個工作spring-security配置,它包裝了我的基於球衣的REST端點並允許方法級別的訪問。如何使用spring-security設置JerseyTest?

與迅速重現該問題所需的一切示例項目:https://github.com/pulkitsinghal/dummy-rest-api

// Server-Side jersey resource 
@GET 
@Path("/protected/myendpoint/") 
@PreAuthorize("hasRole('DUMMY')") 
public String getMyEndpoint(){ 
    return "blah"; 
} 

但對於保護端點寫理智測試時,我遇到了以下異常這只發生在單元測試

Caused by: 
org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: 
An Authentication object was not found in the SecurityContext 

下面是基於JerseyTest的單元測試類的樣子:

@Test 
public void testProtectedEndpoint() { 
    WebResource webResource = resource(); 
    webResource.addFilter(new HTTPBasicAuthFilter("username", "password")); 
    String responseMsg = webResource 
       .path("protected/myendpoint/") 
       .get(String.class); 
    System.out.println(responseMsg); 
} 

當彈簧安全保護端點設置爲JerseyTest時,是否有其他人遇到此問題?可以做些什麼呢?

我遠程看到這裏的一些連接:Spring Test & Security: How to mock authentication?但我沒有達到我可以在該線程中發生的事情的頭或尾的水平。思考?

+1

您可以發佈異常的完整堆棧跟蹤以及您的Spring Security配置嗎?另外,您使用的是Spring,Spring Security和Jersey的哪些版本? –

+0

添加了一個工作示例項目,演示單元測試運行時的問題,在這裏:https://github.com/pulkitsinghal/dummy-rest-api – pulkitsinghal

+0

是這種單元測試,這是不會工作的'GrizzlyWebTestContainerFactory',不管是什麼? – pulkitsinghal

回答

1

理想我運行通過默認的Maven生命週期測試時,要像GrizzlyWebTestContainerFactory單獨的容器作爲測試Web服務器:mvn clean test

但我想,如果沒有正確的答案,這則與使用ExternalTestContainerFactory作爲一種解決方法測試Web服務器必須做的:

$ mvn clean package -DskipTests && (nohup foreman start &) 
$ mvn -Djersey.test.containerFactory=com.sun.jersey.test.framework.spi.container.external.ExternalTestContainerFactory \ 
    -Djersey.test.port=5000 \ 
    -Djersey.test.host=localhost \ 
    test 

注:對於那些不熟悉foreman start只是把它當作tomcat start在這種使用情況下的所有密集的目的。

這仍然可以防止checkins掌握如果測試被破壞,並且spring-security不會在外部tomcat上禁用,所以我認爲它可以解決問題。它有點煩人總是去找到tomcat/java後臺進程的pid,然後殺掉它以便後續清理。

1

JerseyTest在默認情況下在Grizzly上運行,並且您的寧靜Web服務在Tomcat上給出彈簧安全設置 - 作爲示例。所以,請檢查兩個servlet服務器是否具有相同的設置。

+0

這很有趣!請幫助我理解,如果我啓動JerseyTest並以Grizzly開始,那麼爲什麼tomcat會啓動spring-security配置呢?我非常肯定,灰熊負責啓動服務器和測試。 – pulkitsinghal

+0

如果灰熊是你的生產服務器和登臺服務器,那很好,也不需要那種類型的tomcat。因此,如果它與生產設置相同,請檢查JerseyTest的子類上的設置。 – feuyeux

+0

這可能對你有幫助: https://github.com/alesaudate/kickstart-springjerseyhibernate/blob/master/src/test/java/com/alesaudate/samples/test/client/PersonClientTest.java – Muthu