简体   繁体   English

删除 Spring 启动测试上的“使用默认安全密码”

[英]Remove "Using default security password" on Spring Boot test

I have a multi module project, I noticed that when I run my tests (for example the tests annotated with @WebMvcTest ) I get this message我有一个多模块项目,我注意到当我运行我的测试(例如用@WebMvcTest注释的测试)时,我收到了这条消息

    Using generated security password: 12e4c462-385v-12y6-917u-e8u5rte36ooi
        
This generated password is for development use only. Your security configuration must be updated before running your application in production.

How do i remove it?我该如何删除它? I think the "problem" is just that having a multi module project, in some tests, the class implementing UserDetailsService is not found because it is part of a different module and therefore the package is not scanned.我认为“问题”只是有一个多模块项目,在某些测试中,没有找到实现UserDetailsService ervice 的 class 因为它是不同模块的一部分,因此不会扫描 package。 Is it enough for me to just ignore the message?我是否足以忽略该消息? Actually this didn't happen before, it has happened since I removed a bean, probably useless, inside the WebSecuriyConfig class which extends the WebSecurityConfigurerAdapter .实际上这在以前没有发生过,自从我在扩展WebSecurityConfigurerAdapterWebSecuriyConfig class 中删除了一个可能没用的 bean 后就发生了这种情况。

     @Bean
     @Override
     public AuthenticationManager authenticationManagerBean() throws Exception {
         return super.authenticationManagerBean();
     }

Since I don't use that bean anywhere in my application.因为我没有在我的应用程序的任何地方使用那个 bean。

The message you're facing is from spring-boot autoconfiguration class - UserDetailsServiceAutoConfiguration .您面临的消息来自 spring-boot 自动配置 class - UserDetailsServiceAutoConfiguration erviceAutoConfiguration 。

It creates and configures InMemoryUserDetailsManager if no beans of types AuthenticationManager , AuthenticationProvider , UserDetailsService , AuthenticationManagerResolver and some other oauth2 and saml2-related beans found in application context.如果在应用程序上下文中找不到AuthenticationManagerAuthenticationProviderUserDetailsService ervice 、 AuthenticationManagerResolver和其他一些与 oauth2 和 saml2 相关的 bean,它会创建并配置InMemoryUserDetailsManager

As clearly stated in this message, it's considered not safe to use this autoconfiguration feature in production , because there's a chance someone will be able to access secured endpoints using default "user" username and password you're seeing (in case it's stolen or exposed).正如此消息中明确指出的那样,在生产中使用此自动配置功能被认为是不安全,因为有人有可能使用您看到的默认“用户”用户名和密码访问受保护的端点(以防它被盗或暴露) )。

To disable this autoconfiguration feature try this:要禁用此自动配置功能,请尝试以下操作:

@SpringBootApplication(exclude = {UserDetailsServiceAutoConfiguration.class})

Security configuration is not loaded by default by @WebMvcTest . @WebMvcTest默认不加载安全配置。 You need to manually @Import your web-security config and then setup test security-context.您需要手动@Import您的网络安全配置,然后设置测试安全上下文。

For configuring OAuth2 test security context, you can use either要配置 OAuth2 测试安全上下文,您可以使用

  • MockMvc request post-processor: jwt() or opaqueToken() from org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors ) MockMvc 请求后处理器:来自org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessorsjwt()opaqueToken() )
  • a test annotation from this repo此 repo中的测试注释

Sample with @WithMockJwtAuth使用@WithMockJwtAuth进行示例

@WebMvcTest()
@Import({ WebSecurityConfig.class })
class GreetingControllerTest {

    @MockBean
    JwtDecoder jwtDecoder;

    @Autowired
    MockMvc mockMvc;

    @Test
    @WithMockJwtAuth(authorities = {"NICE", "AUTHOR"}, claims = @OpenIdClaims(preferred_username = "Tonton Pirate"))
    void whenGrantedNiceRoleThenOk() throws Exception {
        mockMvc.perform(get("/greet")).andExpect(status().isOk())
                .andExpect(content().string("Hi Tonton Pirate! You are granted with: [NICE, AUTHOR]."));
    }

    @Test
    @WithMockJwtAuth(authorities = {"AUTHOR"}, claims = @OpenIdClaims(preferred_username = "Tonton Pirate"))
    void whenNotGrantedNiceRoleThenForbidden() throws Exception {
        mockMvc.perform(get("/greet")).andExpect(status().isForbidden());
    }

    @Test
    void whenAnonymousThenUnauthorized() throws Exception {
        mockMvc.perform(get("/greet")).andExpect(status().isUnauthorized());
    }
}

Same sample with jwt post-processorjwt后处理器相同的示例

@WebMvcTest()
@Import({ WebSecurityConfig.class })
class GreetingControllerTest {

    @MockBean
    JwtDecoder jwtDecoder;

    @Autowired
    MockMvc mockMvc;

    @Test
    void whenGrantedNiceRoleThenOk() throws Exception {
        mockMvc.perform(get("/greet").with(jwt().jwt(jwt -> {
            jwt.claim("preferred_username", "Tonton Pirate");
        }).authorities(List.of(new SimpleGrantedAuthority("NICE"), new SimpleGrantedAuthority("AUTHOR"))))).andExpect(status().isOk())
                .andExpect(content().string("Hi Tonton Pirate! You are granted with: [NICE, AUTHOR]."));
    }

    @Test
    void whenNotGrantedNiceRoleThenForbidden() throws Exception {
        mockMvc.perform(get("/greet").with(jwt().jwt(jwt -> {
            jwt.claim("preferred_username", "Tonton Pirate");
        }).authorities(List.of(new SimpleGrantedAuthority("AUTHOR"))))).andExpect(status().isForbidden());
    }

    @Test
    void whenAnonymousThenUnauthorized() throws Exception {
        mockMvc.perform(get("/greet")).andExpect(status().isUnauthorized());
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM