[英]Test method secured by spring security
I have just added spring security for my project with configuration:我刚刚为我的项目添加了 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();
}
}
And added some dummy methods just to test it:并添加了一些虚拟方法来测试它:
@RestController
public class LoginController {
@PostMapping("/user")
public String userPanel() {
return "userPanel";
}
@PostMapping("/admin")
public String adminPanel() {
return "adminPanel";
}
}
From browser it works okay, so when I login as admin then I can access both endpoints (405 http error code) and when I am login with user and try to access /admin
endpoint then I get 403 Forbidden which is perfectly fine.从浏览器它工作正常,所以当我以管理员身份登录时,我可以访问两个端点(405 http 错误代码),当我以用户身份登录并尝试访问
/admin
端点时,我得到 403 Forbidden 这非常好。 However when I wrote test for it:但是,当我为它编写测试时:
@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");
}
}
both tests are working even when I am trying to access /admin
endpoint with USER
role.即使我尝试使用
USER
角色访问/admin
端点,这两个测试都可以正常工作。 I would expect this test to fail and throw 403 as in browser.我希望这个测试失败并像在浏览器中一样抛出 403。 What's wrong here?
这里有什么问题?
Final response after @crizzis answer: @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();
}
}
You created a plain new LoginController()
, how did you expect it to have security rules applied?您创建了一个普通的
new LoginController()
,您如何期望它应用安全规则?
It's called HttpSecurity
for a reason, you need to make the request via HTTP
for the rules to actually have any effect.它被称为
HttpSecurity
是有原因的,您需要通过HTTP
发出请求才能使规则真正生效。
Instead of interacting with LoginController
directly, add @AutoConfigureMockMvc
and inject MockMvc
into your test.不要直接与
LoginController
交互,而是添加@AutoConfigureMockMvc
并将MockMvc
注入到您的测试中。 Then use it to execute a request against your endpoints.然后使用它对您的端点执行请求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.