说我有这个资源:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
我应该编写测试来确认某些(测试)用户是否从端点获得响应,而某些用户却没有?如果是这样的话:我怎样才能编写这些测试?我尝试过这样的事情:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
但我不确定如何实际测试@RequiresRoles-annotation 的功能.我已经阅读了Shiro关于测试的页面,但是我无法编写失败的测试(例如,对没有WRITE尝试访问角色的主题进行测试/authhello/test).任何提示将不胜感激.
小智 7
我应该测试一下吗?
是.如果您想确保某些角色拥有或不访问您的资源.这将是一个安全集成测试.
我应该如何设置整个应用程序+如果我要测试它,实际上在测试中使用http请求调用它?或者有更简单的方法吗?
这个问题的部分原因是@RequiresAuthentication和@RequiresRoles自己都只是类和方法的元信息.注释本身不提供安全检查功能.
从你的问题不清楚你正在使用什么类型的容器,但我可以猜测它是普通的泽西JAX-RS服务(我是对的吗?).对于Shiro执行安全检查,您应该在端点周围添加一些JAX-RS过滤器(可能还有其他一些方法吗?).要测试安全性,您应该在测试中复制此设置.否则,没有引擎处理您的注释,结果没有安全检查.