azure - 如何使用 @WebMvcTest、MockMvc 和 OAuth 安全性测试 Controller

标签 azure spring-boot spring-security oauth-2.0 junit5

我有一个使用 Kotlin 创建的 Spring Boot 2.4.5 项目 example

src/
├── main/
│   └── kotlin/
│       └── de.mbur.myapp/
│           ├── controller/
│           │   └── WebController.kt
│           ├── security/
│           │   └── WebSecurityConfiguration.kt
│           └── MyApplication.kt
└── test/
    └── kotlin/
        └── de.mbur.myapp/
            ├── controller/
            │   └── WebControllerTest.kt
            ├── security/
            └── MyApplicationTests.kt

安全配置:

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
class WebSecurityConfiguration(private val configurer: AADB2COidcLoginConfigurer) : WebSecurityConfigurerAdapter() {

  override fun configure(http: HttpSecurity) {
    http.authorizeRequests()
      .anyRequest().authenticated()
      .and()
      .apply(configurer)
  }
}

Controller :

@Controller
class WebController {
  private fun initializeModel(model: Model, token: OAuth2AuthenticationToken?) {
    if (token != null) {
      val user = token.principal
      model.addAllAttributes(user.attributes)
      model.addAttribute("grant_type", user.authorities)
      model.addAttribute("name", user.name)
    }
  }

  @GetMapping("/")
  fun index(model: Model, token: OAuth2AuthenticationToken?): String {
    initializeModel(model, token)
    return "home"
  }

}

最后是测试:

@WebMvcTest(WebController::class)
internal class WebControllerTest {

  @Autowired
  private lateinit var mockMvc: MockMvc

  @MockBean
  private lateinit var configurer: AADB2COidcLoginConfigurer

  @Test
  fun testWebController() {
    mockMvc
      .perform(get("/"))
      .andDo(print())
      .andExpect(status().isForbidden)
  }

  @Test
  @WithMockUser
  fun testAuthentication() {
    mockMvc
      .perform(get("/"))
      .andDo(print())
      .andExpect(status().isOk)
  }

}

首先,我必须提到,我必须模拟 AADB2COidcLoginConfigurer 才能使测试 testWebController 运行。

然后我尝试使用 @WithMockUser 注释运行第二个测试,就像我现在从经典的 Spring 安全测试中运行的那样。但这没有用:

Request processing failed; nested exception is java.lang.IllegalStateException: Current user principal is not of type [org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken]: UsernamePasswordAuthenticationToken [Principal=org.springframework.security.core.userdetails.User [Username=user, Password=[PROTECTED], Enabled=true, AccountNonExpired=true, credentialsNonExpired=true, AccountNonLocked=true, Granted Authorities=[ROLE_USER]], Credentials=[PROTECTED], Authenticated=true, Details=null, Granted Authorities=[ROLE_USER]]

当需要 OAuth2AuthenticationToken 时,如何运行类似于 Spring 用户名密码安全性的测试?

最佳答案

您可以使用 RequestPostProcessors 之一由 Spring Security 提供。

fun testAuthentication() {
    mockMvc
      .perform(get("/")
            .with(oauth2Login())
      .andExpect(status().isOk)
  }

关于azure - 如何使用 @WebMvcTest、MockMvc 和 OAuth 安全性测试 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67341050/

相关文章:

java - 保护有状态的 Web 服务

Azure 警报不起作用

java - 如何在 spring boot 中将 cookie 设置为安全标志

spring-boot - 交叉加入 Spring Boot 2.1.4.RELEASE 应用程序

session - 如何防止Grails 3创建 session ?

java - ReactiveSecurityContextHolder.getContext() 为空但@AuthenticationPrincipal 有效

azure - 在Azure中的应用程序网关的ARM中获取动态IP

azure - 是否可以向共享访问策略添加多个事件中心规则?

image - Azure VM 自定义操作系统镜像 ARM 模板部署

java - 通过keycloak管理客户端在keycloak中创建用户返回IllegalArgumentException