SEC-2984: WithMockUser authorities doc

This commit is contained in:
Rob Winch 2015-07-16 08:48:53 -05:00
parent e4517016ca
commit b96cee7950

View File

@ -72,8 +72,8 @@ The following test will be ran as a user with the username "user", the password
@Test
@WithMockUser
public void getMessageWithMockUser() {
String message = messageService.getMessage();
...
String message = messageService.getMessage();
...
}
----
@ -94,7 +94,7 @@ The following test would run with the username "customUser". Again, the user doe
@WithMockUser("customUsername")
public void getMessageWithMockUserCustomUsername() {
String message = messageService.getMessage();
...
...
}
----
@ -111,6 +111,19 @@ public void getMessageWithMockUserCustomUser() {
}
----
If we do not want the value to automatically be prefixed with ROLE_ we can leverage the authorities attribute.
For example, this test will be invoked with the username "admin" and the authorities "USER" and "ADMIN".
[source,java]
----
@Test
@WithMockUser(username = "admin", authorities = { "ADMIN", "USER" })
public void getMessageWithMockUserCustomAuthorities() {
String message = messageService.getMessage();
...
}
----
Of course it can be a bit tedious placing the annotation on every test method.
Instead, we can place the annotation at the class level and every test will use the specified user.
For example, the following would run every test with a user with the username "admin", the password "password", and the roles "ROLE_USER" and "ROLE_ADMIN".
@ -273,7 +286,7 @@ public class CsrfShowcaseTests {
.build();
}
...
...
----
<1> `SecurityMockMvcConfigurers.springSecurity()` will perform all of the initial setup we need to integrate Spring Security with Spring MVC Test
@ -417,7 +430,7 @@ For example, the following will run the test with the user with username "user",
@Test
@WithMockUser
public void requestProtectedUrlWithUser() throws Exception {
mvc
mvc
.perform(get("/"))
...
}
@ -430,7 +443,7 @@ Alternatively, the following will run the test with the user with username "user
@Test
@WithMockUser(roles="ADMIN")
public void requestProtectedUrlWithUser() throws Exception {
mvc
mvc
.perform(get("/"))
...
}