Authenticating in the @WebMvcTest
Learn authentication by simulating a user login.
We'll cover the following
Simulating user login
Since our UserController
has all its methods secured, we need a way to simulate a user logging in so that we can do some actual validation on the controller’s logic.
The Spring Security test has some helper annotations like @WithMockUser
and @WithUserDetails
to help us. In our production security configuration, we use DatabaseUserDetailsService
and ApplicationUserDetails
classes.
As we don’t want to involve a database, we can create a
StubUserDetailsService
alternative for the automated test by:
-
Implementing
UserDetailsService
like our productionDatabaseUserDetailsService
. -
Keeping the users on a
Map
in memory. -
Adding two users in the constructor so they are available for the tests.
-
Using the
users
map to search for a matching user.
Get hands-on with 1200+ tech skills courses.