JUnit5使用Spring安全性测试安全控制器

龙思

我有一个简单的控制器,只能在安全的上下文中访问。在我的应用程序中,我仅将其他URL列入白名单,而不对白名单/user

在单个单元测试中,@GetResponse我得到的Http状态为401而不是200。我希望这样做,因为它是安全的。

当我实际使用登录用户运行该应用程序时,我得到200,并得到一个有效的结果。

如何对请求和其他所有安全控制器路径的行为进行单元测试?

单元测试:

@SpringBootTest
@AutoConfigureMockMvc
class UserControllerTest {

  @InjectMocks
  UserController userController;
  @Autowired
  private MockMvc mockMvc;
  @Autowired
  private ApplicationContext applicationContext;

  @Test
  void getUserNone() throws Exception {

    mockMvc
        .perform(MockMvcRequestBuilders.get("/user"))
        .andExpect(status().isOk());
  }
}

应用程式:

@SpringBootApplication
public class WebApp extends WebSecurityConfigurerAdapter {

  public static void main(final String... args) {
    SpringApplication.run(WebApp.class, args);
  }

  @Override
  protected void configure(final HttpSecurity http) throws Exception {
    http
        .authorizeRequests(a -> a
            .antMatchers("/error", "/css/**", "/webjars/**").permitAll()
            .anyRequest().authenticated()
        )
        .exceptionHandling(e -> e
            .authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
        )
        .oauth2Login();
  }   
}

控制器:

@Controller
public class UserController {

  @GetMapping("/user")
  public @ResponseBody
  Map<String, Object> getUser(@AuthenticationPrincipal final OAuth2User principal) {
    if (principal == null) {
      return Collections.EMPTY_MAP;
    } else {
      return Collections.singletonMap("name", principal.getName());
    }   
  }
}

显然,我可以添加/user到白名单中的路径,但这对于应用程序的任何受保护部分都是不正确的。

福斯托·卡瓦略·马克斯·席尔瓦

您可以使用注释@WithMockUser@WithAnonymousUser这将创建一个Authentication填充在中的伪造物SecurityContext文档可以在这里找到

示例代码:

@Test
@WithMockUser("john")   
void testAuthorize() throws Exception {
        mockMvc
           .perform(MockMvcRequestBuilders.get("/user"))
           .andExpect(status().isOk());
}
@Test
@WithAnonymousUser
void testUnauthorized() throws Exception {
        mockMvc
           .perform(MockMvcRequestBuilders.get("/user"))
           .andExpect(status().isUnauthorized());
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章