我有一个spring-security-OAUT2应用程序,它是一个ResourceServer。我们有一个定制的PrincipalExtractor类来构建定制的主体对象。此自定义主体对象不扩展Principal或UserDetails
class CustomUser{
//some custom fields
}
class CustomPrincipalExtractor implements PrincipalExtractor{
@Override
public CustomUser extractPrincipal(Map<String, Object> map){
return new CustomUser(map);
}
}
class SomeController{
@GetMapping
public ResponseEntity(@AuthenticationPrincipal CustomUser user){
//able to get user object
}
}上面的代码运行良好。现在我想测试控制器,但不能传递CustomUser实例。
@SpringBootTest
@AutoConfigureMockMvc
public class SomeControllerTest{
@Autowired
private MockMvc mockMvc;
@Test
public void test(){
mockMvc.perform(get(...).principal(CANNOT pass CustomUser as it does not implement Principal))
}
}我查看了一些其他解决方案,它们要求拥有自定义的HandlerMethodArgumentResolver,但不确定如何配置自动配置的MockMvc
发布于 2018-10-25 13:38:03
为了完成这项工作,我不得不实现了一些变通方法。
创建了在SecurityContext中设置身份验证对象的模拟筛选器。以下是代码
public class MockSpringSecurityFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) {}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
SecurityContextHolder.getContext()
.setAuthentication((Authentication) ((HttpServletRequest) req).getUserPrincipal());
chain.doFilter(req, res);
}
@Override
public void destroy() {
SecurityContextHolder.clearContext();
}
}在测试中
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(context)
.apply(springSecurity(new MockSpringSecurityFilter()))
.build();
}
@Test
public void test(){
mockMvc.perform(get(...)
.principal(new UsernamePasswordAuthenticationToken(new CustomUser(), null))...
}https://stackoverflow.com/questions/52180555
复制相似问题