我有一个使用 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/