程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了在Spring Boot 1.4中测试安全性大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决在Spring Boot 1.4中测试安全性?

开发过程中遇到在Spring Boot 1.4中测试安全性的问题如何解决?下面主要结合日常开发的经验,给出你关于在Spring Boot 1.4中测试安全性的解决方法建议,希望对你解决在Spring Boot 1.4中测试安全性有所启发或帮助;

WebMvcTest只会加载您的控制器,而不会加载其他东西(这就是我们称其为切片的原因)。我们无法确定您需要配置的哪一部分,而不需要。如果安全配置不在主目录上@SpringBootApplication,则必须显式导入它。否则,Spring Boot将启用默认安全设置。

如果您使用的是OAuth之类的东西,那是一件好事,因为您真的不想开始将其用于模拟测试。如果添加@import(SecurityConfig.class)到测试中会怎样?

解决方法

我正在尝试@WebMvcTest使用在SecurityConfig类中定义的自定义安全设置 进行测试:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(httpSecurity http) throws Exception {
        http.authorizerequests().antMatchers("/admin*").access("hasRole('ADMIN')").antMatchers("/**").permitAll().and().formLogin();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("user").password("password").roles("ADMIN");
    }
}

测试类是:

@RunWith(SpringRunner.class)
@WebMvcTest(value = ExampleController.class)
public class ExampleControllermockR_545_11845@VCTest {

    @Autowired
    private mockR_545_11845@vc mockR_545_11845@vc;

    @Test
    public void indexTest() throws Exception {
        mockR_545_11845@vc.perform(get("/"))
        .andExpect(status().isOk())
        .andExpect(view().name("index"));
    }

    @Test
    public void adminTestWithoutAuthentication() throws Exception {
        mockR_545_11845@vc.perform(get("/admin"))
        .andExpect(status().is3xxRedirection()); //login form redirect
    }

    @Test
    @WithmockUser(username="example",password="password",roles={"ANONymOUS"})
    public void adminTestWithBadAuthentication() throws Exception {
        mockR_545_11845@vc.perform(get("/admin"))
        .andExpect(status().isForbidden());
    }

    @Test
    @WithmockUser(username="user",roles={"ADMIN"})
    public void adminTestWithAuthentication() throws Exception {
        mockR_545_11845@vc.perform(get("/admin"))
        .andExpect(status().isOk())
        .andExpect(view().name("admin"))
        .andExpect(model().attributeExists("name"))
        .andExpect(model().attribute("name",is("user")));
    }
}

测试失败,因为它们使用的是Spring Boot的默认安全设置。

我可以使用@SpringBootTest+ 修复@AutoConfiguremockR_545_11845@vc它,但是在不运行所有自动配置的情况下进行测试将很有趣。

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.mock)
@AutoConfiguremockR_545_11845@vc
public class ExampleControllerSpringBootTest {

    @Autowired
    private mockR_545_11845@vc mockR_545_11845@vc;

    // tests
}

有什么方法@WebMvcTest可以使用在SecurityConfig课堂上定义的设置?

大佬总结

以上是大佬教程为你收集整理的在Spring Boot 1.4中测试安全性全部内容,希望文章能够帮你解决在Spring Boot 1.4中测试安全性所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。