2017-10-06 106 views
5

說我有這個資源:Shiro:如何爲使用@RequiresRoles保護的端點編寫測試?

import javax.ws.rs.GET; 
import javax.ws.rs.Path; 
import javax.ws.rs.PathParam; 
import javax.ws.rs.Produces; 
import javax.ws.rs.core.MediaType; 
import javax.ws.rs.core.Response; 

import org.apache.shiro.authz.annotation.RequiresAuthentication; 
import org.apache.shiro.authz.annotation.RequiresRoles; 

import io.swagger.annotations.Api; 
import io.swagger.annotations.ApiOperation; 

@Path("/authhello") 
@Api(value = "hello", description = "Simple endpoints for testing api authentification", 
    hidden = true) 
@Produces(MediaType.APPLICATION_JSON) 
@RequiresAuthentication 
public class AuthenticatedHelloWorldResource { 

    private static final String READ = "READ"; 
    private static final String WRITE = "WRITE"; 

    @GET 
    @ApiOperation(value = "helloworld", 
     notes = "Simple hello world.", 
     response = String.class) 
    @RequiresRoles(READ) 
    public Response helloWorld() { 
    String hello = "Hello world!"; 
    return Response.status(Response.Status.OK).entity(hello).build(); 
    } 

    @GET 
    @Path("/{param}") 
    @ApiOperation(value = "helloReply", 
     notes = "Returns Hello you! and {param}", 
     response = String.class) 
    @RequiresRoles(WRITE) 
    public Response getMsg(@PathParam("param") String msg) { 
    String output = "Hello you! " + msg; 
    return Response.status(Response.Status.OK).entity(output).build(); 
    } 
} 

我應該寫確認測試,某些(測試)用戶從端點的響應,並且某些用戶不?如果是這樣的話:我該如何編寫這些測試?我已經試過這樣的事情:

import javax.ws.rs.core.Application; 

import org.glassfish.jersey.server.ResourceConfig; 
import org.junit.Test; 

import com.cognite.api.shiro.AbstractShiroTest; 

import static org.junit.Assert.assertEquals; 

public class AuthenticatedHelloWorldTest extends AbstractShiroTest { 

    @Override 
    protected Application configure() { 
    return new ResourceConfig(AuthenticatedHelloWorldResource.class); 
    } 

    @Test 
    public void testAuthenticatedReadHelloWorld() { 
    final String hello = target("/authhello").request().get(String.class); 
    assertEquals("Hello world!", hello); 
    } 

    @Test 
    public void testAuthenticatedWriteHelloWorld() { 
    final String hello = target("/authhello/test").request().get(String.class); 
    assertEquals("Hello you! test", hello); 
    } 

} 

,但我不知道如何實際測試@RequiresRoles -annotation的功能。我已閱讀Shiro's page on testing,但我無法寫出失敗的測試(例如,對沒有WRITE角色的主題嘗試訪問/authhello/test)的測試。任何提示將不勝感激。

回答

6

我應該測試一下嗎?

是的。如果您想確保某些角色將擁有或無法訪問您的資源。這將是一個安全集成測試。

我應該如何設置整個應用程序+在測試中實際使用http請求調用它,如果我要測試它?還是有更簡單的方法?

問題的一部分是,@RequiresAuthentication@RequiresRoles本身只是類和方法元信息。註釋本身不提供安全檢查功能。

從你的問題中不清楚你正在使用什麼類型的容器,但我可以猜測它是普通的Jersey JAX-RS服務(對嗎?)。對於Shiro執行安全檢查,您應該在您的端點周圍添加一些JAX-RS過濾器(或許有其他方式?)。爲了測試安全性,您應該在測試中複製此設置。否則,沒有引擎處理您的註釋,並因此沒有安全檢查。

+0

謝謝你花時間回答。經過一番認真的挖掘和閱讀之後,我意識到我正如你所說,錯過了一些設置代碼。我設法在我的測試中複製了在應用程序中完成的設置(儘管很遺憾,我無法在此分享示例)。 – L42