Nói rằng tôi có tài nguyên này:Shiro: Làm thế nào để viết một bài kiểm tra cho một điểm cuối được bảo vệ bằng @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();
}
}
Tôi có nên viết bài kiểm tra đó xác nhận rằng nhất định (thử nghiệm) người dùng có được một phản ứng từ các thiết bị đầu cuối, và người dùng nhất định không? Và nếu vậy: Làm thế nào tôi có thể viết những bài kiểm tra đó? Tôi đã thử một cái gì đó như thế này:
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);
}
}
nhưng tôi không chắc chắn làm thế nào để thực sự kiểm tra chức năng của @RequiresRoles
-annotation. Tôi đã đọc Shiro's page on testing nhưng tôi chưa thể viết bài kiểm tra không thành công (ví dụ: kiểm tra đối tượng không có vai trò WRITE
đang cố gắng truy cập /authhello/test
). Bất kỳ lời khuyên sẽ được đánh giá cao.
Cảm ơn bạn đã dành thời gian trả lời. Sau khi một số đào sâu và đọc tôi nhận ra rằng tôi đã, như bạn nói, thiếu một số mã thiết lập. Tôi quản lý để tái tạo các thiết lập được thực hiện trong các ứng dụng trong thử nghiệm của tôi (mặc dù tiếc là tôi không thể chia sẻ một ví dụ ở đây). – L42