Spring 3 MVC Controller integration test - inject Principal into method

那年仲夏 提交于 2019-12-04 06:19:08

After a quick look into Spring sources this should work:

request.setUserPrincipal(somePrincipal);

I've tried to do this some time ago, here is the method i used to set up authentication.

protected void setSecurityContext(String login){
            userDetailsTest = userManager.loadUserByUsername(login);
            TestingAuthenticationToken testingAuthenticationToken = new TestingAuthenticationToken(userDetailsTest, userDetailsTest.getAuthorities());
            SecurityContext securityContext = new SecurityContextImpl();
            securityContext.setAuthentication((Authentication) testingAuthenticationToken);
            SecurityContextHolder.setContext(securityContext);
         } 

Then i just call it in the @Before method of the test. Hope it helps.

I do something like this in my tests prior to calling code using Spring Security (such as the Principal parameter resolver you are testing):

SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("wiseau", "Love is blind"));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!