我正在使用Spring 3.1.0.RELEASE和Spring Security 3.1。我想将我的Spring用户(即当前登录的用户)注入控制器。我想这样做而不是使用
SecurityContextHolder.getContext().getAuthentication().getPrincipal();
因为它允许我使用JUnit更轻松地测试控制器。但是,我的当前设置有问题。我的问题是,将我的用户(每个请求)注入我的控制器的正确方法是什么?在我的应用程序上下文文件中,我有......
<bean id="userDetails" class="com.myco.eventmaven.security.SecurityHolder" factory-method="getUserDetails" scope="request">
<aop:scoped-proxy />
</bean>
我将工厂类定义为......
public class SecurityHolder {
@Autowired
private static UserService userService;
public static MyUserDetails getUserDetails() {
final Authentication a = SecurityContextHolder.getContext().getAuthentication();
if (a == null) {
return null;
} else {
final MyUserDetails reg = (MyUserDetails) a.getPrincipal();
final int userId = reg.getId();
final MyUserDetails foundUser = userService.findUserById(userId);
return foundUser;
} // if
} // getUserDetails
}
但工厂类重复死亡,因为“userService”无法自动装配(值始终为null)。我正在寻找一种更好的方法来完成所有这些,也可以轻松地集成到我的JUnit测试中。有什么想法吗?
编辑:这是我正在寻找的JUnit测试......
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "file:src/test/resources/testApplicationContext.xml" })
public class UserEventFeedsControllerTest extends AbstractTransactionalJUnit4SpringContextTests {
private MockHttpServletRequest request;
private MockHttpServletResponse response;
...
@Autowired
private RequestMappingHandlerAdapter handlerAdapter;
@Autowired
private RequestMappingHandlerMapping handlerMapping;
@Before
public void setUp() {
...
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
}
...
@Test
public void testSubmitUserEventFeedsForm() throws Exception {
request.setRequestURI("/eventfeeds.jsp");
request.setMethod("POST");
final List<EventFeed> allEventFeeds = getAllEventFeeds();
request.setParameter("userEventFeeds", allEventFeeds.get(0).getId().toString());
final Object handler = handlerMapping.getHandler(request).getHandler();
final ModelAndView mav = handlerAdapter.handle(request, response, handler);
assertViewName(mav, "user/eventfeeds");
}
答案 0 :(得分:10)
您无法自动加载static
个字段。有一些解决方法,但我不想向你展示......
有许多方法可以更轻松,更优雅地访问当前用户:
将Principal
注入您的控制器(请参阅When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?):
public ModelAndView showResults(final HttpServletRequest request, Principal principal) {
final String currentUser = principal.getName();
UserDetails ud = ((Authentication)principal).getPrincipal()
在SecurityContext
替换contextHolderStrategy
中的内置SecurityContextHolder
以进行测试