Reputation: 1701
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?
Upvotes: 2
Views: 1919
Reputation: 1701
An alternative solution, that I found and adapted to my use-case is this:
import org.springframework.security.test.context.support.WithSecurityContext
@Retention(AnnotationRetention.RUNTIME)
@WithSecurityContext(factory = WithMockOAuth2SecurityContextFactory::class)
annotation class WithMockOAuth2
import org.springframework.security.core.context.SecurityContext
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken
import org.springframework.security.oauth2.core.oidc.OidcIdToken
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser
import org.springframework.security.test.context.support.WithSecurityContextFactory
class WithMockOAuth2SecurityContextFactory : WithSecurityContextFactory<WithMockOAuth2?> {
override fun createSecurityContext(mockOAuth2: WithMockOAuth2?): SecurityContext {
val context = SecurityContextHolder.createEmptyContext()
if (mockOAuth2 != null) {
val authorities = null
val idToken = OidcIdToken
.withTokenValue("test")
.claim("sub", "test")
.build()
val principal = DefaultOidcUser(authorities, idToken)
val auth = OAuth2AuthenticationToken(principal, authorities, "test")
context.authentication = auth
}
return context
}
}
@Test
@WithMockOAuth2
fun testAuthentication() {
mockMvc
But the other one is shorter and works fine...
This one may be more flexible if one needs to test specific roles, scopes or names...
Upvotes: 0
Reputation: 6499
You can use one of the RequestPostProcessors
provided by Spring Security.
fun testAuthentication() {
mockMvc
.perform(get("/")
.with(oauth2Login())
.andExpect(status().isOk)
}
Upvotes: 2