【发布时间】:2021-07-24 05:16:03
【问题描述】:
我有一个使用 example 创建的带有 Kotlin 的 Spring Boot 2.4.5 项目
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
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 用户名密码安全性的测试?
【问题讨论】:
标签: azure spring-boot spring-security oauth-2.0 junit5