用Spring Security 保护的测试方法

shyt4zoc  于 2021-07-13  发布在  Java
关注(0)|答案(0)|浏览(181)

我刚刚为我的项目添加了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";
    }
}

从浏览器它可以正常工作,所以当我以管理员身份登录时,我可以访问两个端点(405http错误代码),当我以用户身份登录并尝试访问时 /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 端点 USER 角色。我希望这个测试失败并抛出403作为浏览器。这里怎么了?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题