Test Spring Security Rules in a Web Slice With RestAssuredMockMvc
Test a Spring Boot controller with its real Spring MVC and Spring Security configuration but no server, using @WebMvcTest, RestAssuredMockMvc and Spring Security's jwt() post-processor, covering readers, writers, 401, 403 insufficient_scope and problem details.
The previous section tested the accounts controller alone: fast, but blind to security. In this service, security is the most important rule of all. Reading accounts needs one scope, and opening an account another, and those rules live in a Spring Security configuration, not in the controller. To test them, you need Spring’s web layer and the security filter chain, but not the whole application, and not a real token from a real authorization server. In this guide, you’ll start a web slice, stand in for the token, and test every rule.
Level: Advanced · Time: 25 minutes · Part of: Module 11: Spring Boot Integration, section 2
What You’ll Build
You’ll build a test class called WebMvcSliceTest with five tests: a reader lists accounts, a request without a token gets 401, a reader who tries to open an account gets 403, a writer opens one, and an unknown account is a problem detail.
The 403 names the missing scope, as RFC 6750 requires:
1
2
3
4
POST /api/v1/accounts
HTTP/1.1 403 Forbidden
WWW-Authenticate: Bearer error="insufficient_scope", error_description="The request requires higher privileges than provided by the access token.", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1"
When you’re done, Maven reports five passing tests:
1
2
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
In this guide, you will:
- Start a web slice.
- Test the security rules.
- Check errors as problem details.
What You Need
- About 25 minutes
- JDK 26 or later
- Maven 3.9 or later
- An IDE (IntelliJ IDEA, VS Code or Eclipse)
- Knowledge: you can test a controller with
RestAssuredMockMvc, as taught in Test a Spring Controller With RestAssuredMockMvc in Standalone Mode, and you know what401and403 insufficient_scopemean, from Write Negative Security Tests for OAuth 2.0 in REST Assured.
How to Complete This Guide
You can work through this guide in one of two ways:
- Build it step by step: create
WebMvcSliceTestin a newsection_02package next to the class from the previous section, and follow every heading below. - Skip ahead: open the finished class (
WebMvcSliceTest.java) and read along. You can run it at any time with the command in Run the Tests.
Get the code: if you haven’t cloned the examples repository yet, follow the steps in Test a Spring Controller With RestAssuredMockMvc in Standalone Mode.
Out of scope: this guide doesn’t validate real tokens: signature, expiry and audience are tested end to end in Test Spring Boot on a Random Port With REST Assured and Real Tokens.
Understand Web Slices
The problem. Standalone mode leaves out Spring Security, so it can’t prove who may call an endpoint. A full application test can, but it needs a server, a port and real signed tokens. For authorisation rules, both are the wrong size.
The concept. @WebMvcTest is a Spring Boot test annotation that starts a slice of the application: a Spring context with only the web layer.
- Included: the named controller, Spring MVC’s configuration, JSON conversion, error handling with problem details, and Spring Security’s filter chain.
- Left out: services, repositories and other beans, unless the test imports them.
- No server: requests go through
MockMvc, as in the previous section.
Spring Security’s test support then stands in for the token. jwt(), from SecurityMockMvcRequestPostProcessors, is a request post-processor: it puts an authenticated JWT principal with the given authorities directly on the request. No token is signed, sent or decoded.
When to use each. Test authorisation rules, status codes and error formats in a web slice. Test token validation, such as signature, expiry and audience, against a running server with real tokens.
Test the rules with a stand-in token, and the token itself somewhere else.
Meet the API Under Test
The controller is the same AccountController. SecurityConfig makes the service an OAuth 2.0 resource server:
1
2
3
4
5
6
http.authorizeHttpRequests(authorize -> authorize
.requestMatchers(HttpMethod.GET, "/api/v1/accounts", "/api/v1/accounts/**").hasAuthority("SCOPE_accounts:read")
.requestMatchers(HttpMethod.POST, "/api/v1/accounts").hasAuthority("SCOPE_accounts:write")
.requestMatchers("/error").permitAll()
.anyRequest().denyAll())
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))
Spring Security turns each scope in a token into an authority with the prefix SCOPE_. The answers:
| Request | Answer |
|---|---|
| No token | 401 with WWW-Authenticate: Bearer resource_metadata="http://localhost/.well-known/oauth-protected-resource" |
| A token without the scope | 403 with WWW-Authenticate: Bearer error="insufficient_scope", .. |
| Any other method or path, whatever the scopes | 403 (denyAll()) |
| An unknown account, with the right scope | 404 as application/problem+json |
The 401 and 403 have empty bodies: security answers in its headers. The resource_metadata parameter points at the service’s metadata, as RFC 9728 defines; Spring Security adds it.
Your tests check these values:
- The status and the
WWW-Authenticateheader. - The accounts’
ids for a reader, and201for a writer. - The problem detail’s
detailfor an unknown account.
Start a Web Slice
Set Up the Test Class
Goal: start the web layer with the controller, the real security configuration and the service.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.javanibble.module_11.section_02;
import static io.restassured.module.mockmvc.RestAssuredMockMvc.given;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.startsWith;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt;
import com.javanibble.accounts.AccountController;
import com.javanibble.accounts.AccountService;
import com.javanibble.accounts.SecurityConfig;
import io.restassured.http.ContentType;
import io.restassured.module.mockmvc.specification.MockMvcRequestSpecification;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
import org.springframework.context.annotation.Import;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.JwtRequestPostProcessor;
import org.springframework.test.web.servlet.MockMvc;
@WebMvcTest(AccountController.class)
@Import({SecurityConfig.class, AccountService.class})
class WebMvcSliceTest {
@Autowired
private MockMvc mockMvc;
private MockMvcRequestSpecification accounts() {
return given().mockMvc(mockMvc);
}
}
What’s happening:
@WebMvcTest(AccountController.class)starts the web layer with that one controller. In Spring Boot 4, it lives inorg.springframework.boot.webmvc.test.autoconfigure; the Spring Boot 3 package is gone.@Import(..)adds the security configuration and the service, which the slice would otherwise leave out. Without the service, the context fails withNoSuchBeanDefinitionException: No qualifying bean of type 'com.javanibble.accounts.AccountService'.given().mockMvc(mockMvc)hands REST Assured theMockMvcthat Spring built, with the security filter chain in it.
Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.
Stand In for the Token
Goal: build a stand-in token with the scopes a test needs.
Add this helper to the class:
1
2
3
4
5
6
7
private static JwtRequestPostProcessor tokenWith(String... scopes) {
SimpleGrantedAuthority[] authorities = new SimpleGrantedAuthority[scopes.length];
for (int i = 0; i < scopes.length; i++) {
authorities[i] = new SimpleGrantedAuthority("SCOPE_" + scopes[i]);
}
return jwt().authorities(authorities);
}
What’s happening:
jwt().authorities(..)builds a post-processor that authenticates the request as a JWT principal with exactly these authorities.tokenWith(..)adds theSCOPE_prefix, so the authorities matchhasAuthority("SCOPE_accounts:read").- The test needs no authorization server and no signing key.
Checkpoint: the class still compiles.
Add the
SCOPE_prefix. A stand-in with the authorityaccounts:read, without the prefix, got403 insufficient_scopeon a read. So didjwt()with no authorities set, which has a default authority of its own that the rules don’t accept.
Test the Security Rules
Let a Reader List Accounts
Goal: prove a token with accounts:read can list the accounts.
Add this test to the class:
1
2
3
4
5
6
7
8
9
10
@Test
void aReaderCanListAccounts() {
accounts()
.postProcessors(tokenWith("accounts:read"))
.when()
.get("/api/v1/accounts")
.then()
.statusCode(200)
.body("id", contains("acc-1001", "acc-1002"));
}
What’s happening:
postProcessors(..)applies the stand-in token to this request.- The request goes through the real filter chain, which finds the authority
SCOPE_accounts:readand lets it through to the controller. contains(..)checks the ids, in order.
Checkpoint: run WebMvcSliceTest from your IDE. One test runs and passes, after the slice starts in about a second.
The slice’s
AccountServiceis one bean, shared by every test in the class, and Spring caches the context between them. WhenaWriterCanOpenAccountswas made to run first, this test failed withActual: <[acc-1001, acc-1002, acc-1003]>. It passes because JUnit happens to run it earlier. UsehasItems(..)for a list other tests can change, or give each test a fresh service.
Refuse a Request Without a Token
Goal: prove a request without a token gets 401.
Add this test to the class:
1
2
3
4
5
6
7
8
9
@Test
void withoutATokenTheAnswerIs401() {
accounts()
.when()
.get("/api/v1/accounts")
.then()
.statusCode(401)
.header("WWW-Authenticate", startsWith("Bearer"));
}
What’s happening:
- With no post-processor, the request is anonymous, and the filter chain answers
401before the controller runs. WWW-Authenticate: Bearertells the client which scheme to use.
Checkpoint: run the class again. Two tests pass.
Refuse a Reader Who Opens an Account
Goal: prove a token with only accounts:read can’t open an account.
Add this test to the class:
1
2
3
4
5
6
7
8
9
10
11
12
@Test
void aReaderCannotOpenAccounts() {
accounts()
.auth().with(tokenWith("accounts:read")) // the same, through auth()
.contentType(ContentType.JSON)
.body("{\"iban\": \"NL20INGB0001234567\", \"owner\": \"Sanne\", \"currency\": \"EUR\"}")
.when()
.post("/api/v1/accounts")
.then()
.statusCode(403)
.header("WWW-Authenticate", containsString("insufficient_scope"));
}
What’s happening:
auth().with(..)applies a post-processor too. It reads like theauth()calls of plain REST Assured, which makes the authentication stand out.- The token is authenticated but lacks
accounts:write, so the answer is403witherror="insufficient_scope", not401.
Checkpoint: run the class again. Three tests pass.
Let a Writer Open an Account
Goal: prove a token with accounts:write can open an account.
Add this test to the class:
1
2
3
4
5
6
7
8
9
10
11
@Test
void aWriterCanOpenAccounts() {
accounts()
.postProcessors(tokenWith("accounts:write"))
.contentType(ContentType.JSON)
.body("{\"iban\": \"NL20INGB0001234567\", \"owner\": \"Sanne\", \"currency\": \"EUR\"}")
.when()
.post("/api/v1/accounts")
.then()
.statusCode(201);
}
What’s happening:
- The same request as the reader’s, with the other scope, gets
201. Together, the two tests pin down the rule from both sides.
Checkpoint: run the class again. Four tests pass.
Check Errors as Problem Details
Read an Unknown Account
Goal: check the error format standalone mode couldn’t show.
Add this test to the class:
1
2
3
4
5
6
7
8
9
10
11
@Test
void errorsAreProblemDetails() {
accounts()
.postProcessors(tokenWith("accounts:read"))
.when()
.get("/api/v1/accounts/{id}", "acc-9999")
.then()
.statusCode(404)
.contentType("application/problem+json")
.body("detail", equalTo("Account acc-9999 does not exist"));
}
What’s happening:
- The slice includes Spring Boot’s error handling, and
spring.mvc.problemdetails.enabled=trueturns the controller’sResponseStatusExceptioninto an RFC 9457 problem detail. - The body is
{"detail":"Account acc-9999 does not exist","instance":"/api/v1/accounts/acc-9999","status":404,"title":"Not Found"}. In standalone mode, it was empty.
Checkpoint: run the class again. All five tests pass.
The slice imports the real
SecurityConfig, including itsJwtDecoder. A request with a realAuthorization: Bearer not-a-real-tokenheader got401witherror="invalid_token", error_description="An error occurred while attempting to decode the Jwt: Malformed token". The stand-in skips decoding; a header doesn’t.
Run the Tests
Run the following command from the repository root:
1
mvn test -pl module-11 -Dtest=WebMvcSliceTest
You should see a result similar to the following, after Spring Boot’s start-up log:
1
2
3
4
5
6
[INFO] Running com.javanibble.module_11.section_02.WebMvcSliceTest
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.167 s -- in com.javanibble.module_11.section_02.WebMvcSliceTest
[INFO]
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
Make a Test Fail
Change the import to @Import(AccountService.class), leaving out SecurityConfig, and run the command again. You should see a result similar to the following:
1
2
3
4
5
6
7
8
9
10
11
[ERROR] Failures:
[ERROR] WebMvcSliceTest.aReaderCanListAccounts:61 1 expectation failed.
JSON path id doesn't match.
Expected: iterable containing ["acc-1001", "acc-1002"]
Actual: <[acc-1001, acc-1002, acc-1003]>
[ERROR] WebMvcSliceTest.aReaderCannotOpenAccounts:83 1 expectation failed.
Expected status code <403> but was <201>.
[ERROR] WebMvcSliceTest.withoutATokenTheAnswerIs401:71 1 expectation failed.
Expected header "WWW-Authenticate" was not a string starting with "Bearer", was "Basic realm="Realm", charset="UTF-8"". ...
Without your configuration, the slice uses Spring Boot’s default security: any authenticated user may do anything, and an anonymous one is asked for Basic credentials. So the reader opened an account with 201, and the 401 asks for Basic, not Bearer. The reader’s account then showed up in the list, which is the shared-service problem from the danger callout. The tests checked rules that weren’t yours.
Put SecurityConfig.class back in the import and run the tests once more to confirm they pass.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
WWW-Authenticate: Basic realm="Realm" | SecurityConfig isn’t imported, so Spring Boot’s default security applies | Add it to @Import(..) |
NoSuchBeanDefinitionException: .. AccountService | The slice doesn’t create services | Import the service, or provide a mock with @MockitoBean |
403 insufficient_scope with the right scope | The authority lacks the SCOPE_ prefix | Build it with tokenWith(..) |
| A list has more items than expected | Another test changed the shared service | Use hasItems(..), or a fresh service per test |
401 invalid_token .. Malformed token | A real Authorization header instead of jwt() | Use postProcessors(..) or auth().with(..) |
Try It Yourself
Exercise 1: A Writer Can’t Read
Add a test called aWriterCannotReadAccounts. List the accounts with a stand-in token that has only accounts:write, and check that the answer is 403 with insufficient_scope.
Hint
Use tokenWith("accounts:write") and get("/api/v1/accounts"). Scopes don’t imply each other: writing doesn’t include reading.
Solution
1
2
3
4
5
6
7
8
9
10
@Test
void aWriterCannotReadAccounts() {
accounts()
.postProcessors(tokenWith("accounts:write"))
.when()
.get("/api/v1/accounts")
.then()
.statusCode(403)
.header("WWW-Authenticate", containsString("insufficient_scope"));
}
Exercise 2: Everything Else Is Denied
Add a test called anyOtherRequestIsDenied. Send DELETE /api/v1/accounts/acc-1001 with a stand-in token that has both scopes, and check that the answer is 403.
Hint
Pass both scopes: tokenWith("accounts:read", "accounts:write"). anyRequest().denyAll() refuses the request before Spring MVC looks for a handler, so it’s 403, not 405.
Solution
1
2
3
4
5
6
7
8
9
@Test
void anyOtherRequestIsDenied() {
accounts()
.postProcessors(tokenWith("accounts:read", "accounts:write"))
.when()
.delete("/api/v1/accounts/{id}", "acc-1001")
.then()
.statusCode(403);
}
Summary
You built WebMvcSliceTest, which tests the accounts service’s security rules through its real Spring MVC and Spring Security configuration, with no server and no real tokens: readers read, writers write, the anonymous get 401, the wrong scope gets 403 insufficient_scope, and errors are problem details.
@WebMvcTest(..)starts the web layer with the named controller; import the security configuration and the services it needs.given().mockMvc(mockMvc)hands Spring’sMockMvctoRestAssuredMockMvc.jwt().authorities(..), applied withpostProcessors(..)orauth().with(..), stands in for the token; give authorities theSCOPE_prefix.- The slice shares one context and its beans between tests, so state can leak from one test into another.
- A stand-in token tests the rules, not token validation.
Here are the commands you used in this guide:
1
mvn test -pl module-11 -Dtest=WebMvcSliceTest
What’s Next
Next: continue with Test Spring Boot on a Random Port With REST Assured and Real Tokens, which starts the whole application and tests it with real signed tokens.
The code:
- The finished test class:
WebMvcSliceTest.java - The security rules:
SecurityConfig.java - The code and run commands for this module: Module 11 README
Go deeper:
- Spring Security: Testing OAuth 2.0 With MockMvc, for
jwt()and its options. - Spring Boot: Testing Spring Boot Applications, for
@WebMvcTestand the other slices. - RFC 6750, section 3.1, for
invalid_tokenandinsufficient_scope.
Related guides:
- Write Negative Security Tests for OAuth 2.0 in REST Assured, for the same rules tested over HTTP.
- Generate Dynamic API Tests With REST Assured, for checking every endpoint’s security from a list.
