You have a number of options to associate a user to the current `HttpServletRequest`.
The following example runs as a user (which does not need to exist) whose username is `user`, whose password is `password`, and whose role is `ROLE_USER`:
The support works by associating the user to the `HttpServletRequest`.
To associate the request to the `SecurityContextHolder`, you need to ensure that the `SecurityContextPersistenceFilter` is associated with the `MockMvc` instance.
For example, the following will run as a user (which does not need to exist) with the username "admin", the password "pass", and the roles "ROLE_USER" and "ROLE_ADMIN".
If you have a custom `UserDetails` that you would like to use, you can easily specify that as well.
For example, the following will use the specified `UserDetails` (which does not need to exist) to run with a `UsernamePasswordAuthenticationToken` that has a principal of the specified `UserDetails`:
====
.Java
[source,java,role="primary"]
----
mvc
.perform(get("/").with(user(userDetails)))
----
.Kotlin
[source,kotlin,role="secondary"]
----
mvc.get("/") {
with(user(userDetails))
}
----
====
You can run as anonymous user using the following:
====
.Java
[source,java,role="primary"]
----
mvc
.perform(get("/").with(anonymous()))
----
.Kotlin
[source,kotlin,role="secondary"]
----
mvc.get("/") {
with(anonymous())
}
----
====
This is especially useful if you are running with a default user and wish to process a few requests as an anonymous user.
If you want a custom `Authentication` (which does not need to exist) you can do so using the following:
We can also ensure to run as a specific user for every request by using ``MockMvcBuilders``'s default request.
For example, the following will run as a user (which does not need to exist) with the username "admin", the password "password", and the role "ROLE_ADMIN":
== Running as a User in Spring MVC Test with Annotations
As an alternative to using a `RequestPostProcessor` to create your user, you can use annotations described in xref:servlet/test/method.adoc[Testing Method Security].
For example, the following will run the test with the user with username "user", password "password", and role "ROLE_USER":
====
.Java
[source,java,role="primary"]
----
@Test
@WithMockUser
public void requestProtectedUrlWithUser() throws Exception {
mvc
.perform(get("/"))
...
}
----
.Kotlin
[source,kotlin,role="secondary"]
----
@Test
@WithMockUser
fun requestProtectedUrlWithUser() {
mvc
.get("/")
// ...
}
----
====
Alternatively, the following will run the test with the user with username "user", password "password", and role "ROLE_ADMIN":
====
.Java
[source,java,role="primary"]
----
@Test
@WithMockUser(roles="ADMIN")
public void requestProtectedUrlWithUser() throws Exception {