栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Spring Test返回不安全URL的401

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Test返回不安全URL的401

我发现
Spring文档说的答案是:

@WebMvcTest将自动配置Spring MVC基础结构,并将扫描的bean限制为@ Controller,@ ControllerAdvice,@
JsonComponent,Filter,WebMvcConfigurer和HandlerMethodArgumentResolver。使用此注释时,不会扫描常规@Component
bean。

并根据github中的这个问题:

https://github.com/spring-projects/spring-
boot/issues/5476

如果在类路径中存在spring-security-test(在我的情况下),默认情况下,@WebMvcTest自动配置spring安全性。

因此,由于未选择WebSecurityConfigurer类,因此默认安全性是自动配置的,这就是我收到url中的401的动机,而该问题在我的安全性配置中未得到保护。Spring
Security默认的自动配置通过基本身份验证来保护所有url。

我要解决的问题是用@ContextConfiguration注释类,而@MockBean像在文档中进行了描述:

通常,@ WebMvcTest将限于单个控制器,并与@MockBean结合使用,以为所需的协作者提供模拟实现。

这是测试课

@RunWith(SpringRunner.class)@WebMvcTest@ContextConfiguration(classes={Application.class, MvcConfig.class, SecurityConfig.class})public class ITIndex {    @Autowired    WebApplicationContext context;    MockMvc mockMvc;    @MockBean    UserRegistrationApplicationService userRegistrationApplicationService;    @MockBean    UserDetailsService userDetailsService;    @Before    public void setUp() {        this.mockMvc = MockMvcBuilders  .webAppContextSetup(context)  .apply(springSecurity())  .build();    }    @Test    public void should_render_index() throws Exception {        mockMvc.perform(get("/")) .andExpect(status().isOk()) .andExpect(view().name("index")) .andExpect(content().string(containsString("Login")));    }}

Application,MvcConfig和SecurityConfig都是我的配置类



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/437851.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号