Java 如何在Jersey测试期间设置模拟Spring用户主体?
我正在处理一个内容限制层的代码,它基本上防止在GET响应中返回某些JSON元素 为此,我需要检查Spring的安全上下文提供的经过身份验证的用户主体,定制我的响应,并将其发送回客户端 所以。。。我的问题是,在没有安全上下文的情况下,如何使用JerseyTest实现这一点?我需要以某种方式设置Jersey在处理GET请求时将找到的模拟身份验证主体 这是我的测试:Java 如何在Jersey测试期间设置模拟Spring用户主体?,java,spring,spring-security,jersey,Java,Spring,Spring Security,Jersey,我正在处理一个内容限制层的代码,它基本上防止在GET响应中返回某些JSON元素 为此,我需要检查Spring的安全上下文提供的经过身份验证的用户主体,定制我的响应,并将其发送回客户端 所以。。。我的问题是,在没有安全上下文的情况下,如何使用JerseyTest实现这一点?我需要以某种方式设置Jersey在处理GET请求时将找到的模拟身份验证主体 这是我的测试: import org.junit.Test; import org.springframework.web.context.Contex
import org.junit.Test;
import org.springframework.web.context.ContextLoaderListener;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.spi.spring.container.servlet.SpringServlet;
import com.sun.jersey.test.framework.JerseyTest;
import com.sun.jersey.test.framework.WebAppDescriptor;
public class GroupResourceTest extends JerseyTest {
public GroupResourceTest() throws Exception {
super(new WebAppDescriptor.Builder().contextPath("/api-resources-test")
.contextParam("contextConfigLocation", "file:src/test/resources/applicationContext-test.xml")
.servletClass(SpringServlet.class).contextListenerClass(ContextLoaderListener.class)
.initParam("com.sun.jersey.api.json.POJOMappingFeature", "true").build());
}
@Test
public void testGroupsGET() {
WebResource webResource = resource();
String response = webResource.path("/groups").get(String.class);
System.out.println(response);
}
}
下面是我需要与模拟用户关联的相应资源:
@GET
@Path("/groups")
@Produces({ MediaType.APPLICATION_JSON })
public List<Group> getGroups() {
Authentication user = SecurityContextHolder.getContext().getAuthentication();
// do user-based response here...
}
@GET
@路径(“/组”)
@产生({MediaType.APPLICATION_JSON})
公共列表getGroups(){
身份验证用户=SecurityContextHolder.getContext().getAuthentication();
//在这里做基于用户的响应。。。
}
使用此代码,上面的
user
对象为null
。有什么想法吗?您应该能够通过以下方法实现这一点:
@After
public void cleanup() {
SecurityContextHolder.clearContext();
}
@Test
public void testGroupsGET() {
User user =
new User("user","notused",AuthorityUtils.createAuthorityList("ROLE_USER"));
Authentication auth =
new UsernamePasswordAuthenticationToken(user,user.getPassword(),user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(auth);
WebResource webResource = resource();
String response = webResource.path("/groups").get(String.class);
System.out.println(response);
}
注意:如果您使用自定义UserDetails服务,但不返回用户对象,则可能需要将用户替换为您正在使用的自定义UserDetails。不适用于我。返回的身份验证对象仍然为空。就好像有两个独立的
SecurityContextHolder
实例在运行。换句话说,我在其中一个上设置身份验证对象,而JerseyTest则从另一个上提取。可能吗?