Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 弹簧安全性试验方法_Java_Spring Boot_Unit Testing_Spring Security - Fatal编程技术网

Java 弹簧安全性试验方法

Java 弹簧安全性试验方法,java,spring-boot,unit-testing,spring-security,Java,Spring Boot,Unit Testing,Spring Security,我刚刚为我的项目添加了spring安全配置: @Configuration @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter { private final DataSource dataSource; @Autowired public SecurityConfiguration(DataSource dataSource) {

我刚刚为我的项目添加了spring安全配置:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    private final DataSource dataSource;

    @Autowired
    public SecurityConfiguration(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication()
                .withDefaultSchema()
                .dataSource(dataSource)
                .withUser("user")
                .password("{bcrypt}" + new BCryptPasswordEncoder().encode("password"))
                .roles("USER")
                .and()
                .withUser("admin")
                .password("{bcrypt}" + new BCryptPasswordEncoder().encode("admin"))
                .roles("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/h2-console/**").permitAll()
                .antMatchers("/user").hasAnyRole("USER", "ADMIN")
                .antMatchers("/admin").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
                .formLogin().permitAll();
        http.headers().frameOptions().disable();
    }
}
并添加了一些虚拟方法来测试它:

@RestController
public class LoginController {

    @PostMapping("/user")
    public String userPanel() {
        return "userPanel";
    }

    @PostMapping("/admin")
    public String adminPanel() {
        return "adminPanel";
    }
}
从浏览器中,它可以正常工作,所以当我以管理员身份登录时,我可以访问两个端点(405 http错误代码),当我使用用户登录并尝试访问
/admin
端点时,我会得到403禁止,这是非常好的。然而,当我为它编写测试时:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class SecurityTest {
    private LoginController loginController;

    @Before
    public void setUp(){
        loginController = new LoginController();
    }

    @Test
    @WithMockUser(username = "admin", roles = {"USER", "ADMIN"})
    public void testUserPanel() {
        assertThat(loginController.userPanel()).isEqualTo("userPanel");
    }

    @Test
    @WithMockUser(username = "user", roles = {"USER"})
    public void testAdminPanel() {
        assertThat(loginController.adminPanel()).isEqualTo("adminPanel");
    }
}
即使在我尝试使用
用户
角色访问
/admin
端点时,这两个测试仍在工作。我希望这个测试失败,并抛出403作为在浏览器中。这里怎么了

@crizzis回答后的最终回答:

import com.storageroom.StorageRoomApplication;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = StorageRoomApplication.class)
public class SecurityTest {
    @Autowired
    private WebApplicationContext context;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders
                .webAppContextSetup(context)
                .apply(springSecurity())
                .build();
    }

    @Test
    @WithMockUser(value = "user", roles = {"USER"})
    public void testUserPanelWithUserRole() throws Exception {
        mockMvc
                .perform(
                        post("/user")
                                .contentType(
                                        MediaType.APPLICATION_JSON).
                                content("")).
                andExpect(status().isOk())
                .andReturn().getResponse().getContentAsString();
    }

    @Test
    @WithMockUser(value = "user", roles = {"USER"})
    public void testAdminPanelWithUserRole() throws Exception {
        mockMvc
                .perform(
                        post("/admin")
                                .contentType(
                                        MediaType.APPLICATION_JSON).
                                content("")).
                andExpect(status().isForbidden())
                .andReturn().getResponse().getContentAsString();
    }

    @Test
    @WithMockUser(value = "admin", roles = {"ADMIN"})
    public void testAdminPanelWithAdminRole() throws Exception {
        mockMvc
                .perform(
                        post("/admin")
                                .contentType(
                                        MediaType.APPLICATION_JSON).
                                content("")).
                andExpect(status().isOk())
                .andReturn().getResponse().getContentAsString();
    }
}

您创建了一个普通的
新LoginController()
,您希望它如何应用安全规则

之所以称为
HttpSecurity
,是因为您需要通过
HTTP
发出请求,规则才能真正生效


不要直接与
LoginController
交互,而是添加
@AutoConfigureMockMvc
并将
MockMvc
注入测试。然后使用它对端点执行请求。

是有道理的,但是它给我带来了另一个问题-当尝试
mockMvc=MockMvcBuilders.webAppContextSetup(context.apply)(springSecurity()).build()时
com.storageroom.security.config.SecurityConfiguration中构造函数的参数0出现异常
要求找不到类型为“javax.sql.DataSource”的bean。
看起来
datasourceautocondition
未被提取,您在测试中是否以某种方式排除了它?尝试将
@SpringBootTest(classes=MyApplication.class)
添加到测试中。这将使你的应用程序的整个上下文变得更加生动