-
Hello, I would like to annotate not only controllers, but also services with When I do so, I cannot properly unittest these services in isolation by injecting them directly to tests since I want to be able to properly set up the security context in unit tests, as if I was performing an HTTP call from a test method with I tried building a Ideally |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
/cc @sberyozkin (security) |
Beta Was this translation helpful? Give feedback.
-
Found an answer - I can inject The manually constructed identity will be used for any direct invocations on injected secured beans, and if I perform a HTTP call with RestAssured, the identity will be constructed from the annotations. This can be mixed and matched, so I can "direct-init" using an injected service instance (like inserting database rows through it), and then have that data returned and inspected using RestAssured. @QuarkusTest
class SecuredResourceTest {
@Inject
lateinit var service: SecuredService
@Inject
lateinit var identityAssociation: CurrentIdentityAssociation
@Test
@TestSecurity(user = "Regular User", augmentors = [TestSecurityIdentityAugmentor::class])
@OidcSecurity(
userinfo = [
UserInfo(key = "sub", value = "regularUser"),
UserInfo(key = "email", value = "test@example.com"),
UserInfo(key = "name", value = "Test User Name"),
]
)
fun testWithDirectCallsAndRestassured() {
val userInfoJson = buildJsonObject {
put("sub", "adminUser")
put("email", "admin@example.com")
put("name", "Test Admin Name")
}
val userinfo = UserInfo(userInfoJson.toString())
val identity = QuarkusSecurityIdentity.builder()
.addAttribute("userinfo", userinfo)
.setPrincipal { "Test Admin Name" }
.build()
// assuming the static augmentIdentity() is what TestSecurityIdentityAugmentor calls internally too
identityAssociation.identity = TestSecurityIdentityAugmentor.augmentIdentity(identity)
// uses admin identity from association
service.methodRequiringAdminPrivileges()
// uses user identity constructed from annotations
When {
get("/adminEndpoint") // 403
}
When {
get("/userEndpoint") // 200
}
} |
Beta Was this translation helpful? Give feedback.
Found an answer - I can inject
CurrentIdentityAssociation
into the test and set a manually constructedSecurityIdentity
. This can further be combined with theTestSecurity
andOidcSecurity
annotations on the very same test method.The manually constructed identity will be used for any direct invocations on injected secured beans, and if I perform a HTTP call with RestAssured, the identity will be constructed from the annotations.
This can be mixed and matched, so I can "direct-init" using an injected service instance (like inserting database rows through it), and then have that data returned and inspected using RestAssured.