I have an Spring Boot 2.4.5 project with Kotlin created using this 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
Security Config:
@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"
}
}
And finally the test:
@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)
}
}
First I have to mention that I had to mock the AADB2COidcLoginConfigurer to make the test testWebController run at all.
Then I tried to run the second test with the @WithMockUser annotation as I now it from classical spring security tests. But that did not work:
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]]
How can I run this test similar to Spring username password security when OAuth2AuthenticationToken is expected?