I\'m using spring OAuth2 and JWT tokens to secure an application. I am extending org.springframework.security.core.userdetails in order to add some additional a
You can use the @WithUserDetails
annotation.
If you have a user with the username "user1", then you can annotate your test with @WithUserDetails("user1")
and it will execute with a CustomUser
principal, including the custom attribute "bookId" associated with "user1".
You can find more information about the annotation in the spring-security docs.
If you want more flexibility, you can also use the @WithSecurityContext
annotation.
This allows you to create your own annotation, e.g @WithMockCustomUser
, where you set the security context yourself.
You can find more details in the spring-security docs.
One more option, if you are using MockMvc
to run your tests, it to use a request post processor.
Your test would look like this
mvc
.perform(get("/api/books/1")
.with(user(customUser)));
where customUser
is an instance of CustomUser
that you create in the test.