Scrivio Interview library
CodingIntermediate7 min read · updated 12 November 2026

Your resource server validates JWTs and maps a 'scope' claim to authorities. How would you test authorization rules without a real identity provider?

We test the authorization rules with Spring Security's test support, which puts a ready-made JWT authentication into the request so no identity provider is needed: jwt() for MockMvc and mockJwt() for WebTestClient, each with the authorities or claims we want. We test our own scope-to-authority converter separately with real Jwt objects, test @PreAuthorize methods with @WithMockUser or a custom security context annotation, and keep one integration test that sends a real token signed by a test key so the decoding settings are covered too.

Why this question is asked

A resource server, a service that accepts requests only when they carry a valid access token, has two jobs: decode and validate the token, then decide what the caller may do. In production the token comes from an identity provider such as Keycloak, Okta or Entra ID, but tests that depend on a live provider are slow, flaky and hard to set up for every role we need. Interviewers ask this to see whether we know how to cut that dependency without testing a fake version of our security. In this answer, we will recap how a JWT becomes authorities, test URL rules with MockMvc and WebTestClient, test the converter on its own, test method security, and finish with the one test that uses a real signed token.

1A Quick Recap: From Token to Authorities

A JWT (JSON Web Token) is a signed JSON document. The resource server checks the signature against the provider's public key, checks the expiry, issuer and audience, and then turns the claims into a Jwt object. Claims are the fields inside the token, such as sub for the user and scope for the permissions.

Spring Security then runs a converter that turns the Jwt into an Authentication with a list of GrantedAuthority objects. By default, JwtGrantedAuthoritiesConverter reads the scope claim and adds the prefix SCOPE_, so a token with scope orders.read gives the authority SCOPE_orders.read. Our rules, such as hasAuthority("SCOPE_orders.read"), only ever look at these authorities.

That split is the key to testing. The URL and method rules depend only on the Authentication, so most tests can skip the token entirely and hand Spring a ready-made Authentication. The decoding and the conversion are tested separately, in fewer and more targeted tests.

Step throughWhat each test level covers
  1. Real signed tokenone integration test: signature, issuer, audience, expiry
  2. JwtAuthenticationConverterunit tests with real Jwt objects: claim -> authorities
  3. URL rulesMockMvc jwt() or WebTestClient mockJwt(): 200, 403, 401
  4. Method rules@PreAuthorize on services: @WithMockUser or custom annotation

4 layers, from the top down. Step through them one at a time.

Each layer gets the cheapest test that can still break when it is wrong.

2Testing URL Rules With MockMvc

With MockMvc, the jwt() request post processor from SecurityMockMvcRequestPostProcessors builds a JwtAuthenticationToken and places it in the security context for that one request. The JwtDecoder is never called, so no keys or provider are needed. We should always write the negative case next to the positive one, because a rule that lets everybody in passes every positive test.

Java
@WebMvcTest(OrderController.class)
@Import(SecurityConfig.class)
class OrderSecurityTest {
@Autowired MockMvc mvc;
@MockitoBean OrderService orders;
@Test void readScopeCanList() throws Exception {
mvc.perform(get("/orders")
.with(jwt().authorities(new SimpleGrantedAuthority("SCOPE_orders.read"))))
.andExpect(status().isOk()); // 200
}
@Test void wrongScopeIsForbidden() throws Exception {
mvc.perform(get("/orders")
.with(jwt().authorities(new SimpleGrantedAuthority("SCOPE_profile"))))
.andExpect(status().isForbidden()); // 403
}
@Test void noTokenIsUnauthorized() throws Exception {
mvc.perform(get("/orders")).andExpect(status().isUnauthorized()); // 401
}
@Test void claimsGoThroughOurConverter() throws Exception {
mvc.perform(get("/orders")
.with(jwt().jwt(j -> j.claim("scope", "orders.read"))
.authorities(new OrderAuthoritiesConverter())))
.andExpect(status().isOk()); // 200
}
}

Notice the two styles. authorities(...) sets the authorities directly and is the clearest way to say which permission a test needs. jwt(j -> j.claim(...)) sets claims instead. But there is a catch: when we only set claims, the mock uses Spring's default scope converter, not ours. If our application maps claims in a custom way, we pass our converter with authorities(converter), as in the last test, so the test exercises the same mapping that production uses.

3The Same Idea With WebTestClient

In a reactive application, or when we prefer WebTestClient against a WebFlux controller, SecurityMockServerConfigurers.mockJwt() does the same job. We apply it with mutateWith, which changes the client for one exchange.

Java
client.mutateWith(mockJwt().authorities(new SimpleGrantedAuthority("SCOPE_orders.write")))
.post().uri("/orders").bodyValue(newOrder)
.exchange()
.expectStatus().isCreated(); // 201
client.mutateWith(mockJwt().jwt(j -> j.claim("scope", "orders.read")))
.post().uri("/orders").bodyValue(newOrder)
.exchange()
.expectStatus().isForbidden(); // 403: read scope cannot create

The style is different but the reasoning is the same: we skip decoding, set exactly the authorities the rule cares about, and check both the allowed and the refused case.

4Testing the Converter With Real Jwt Objects

The mock tests above trust that the authorities are right. So the converter that produces them deserves its own unit test. It is a plain function from Jwt to authorities, and Jwt has a builder, so we can create real Jwt objects with exactly the claims a provider sends, including awkward ones such as a space-separated scope string, a roles array, or a missing claim.

Java
@Test void mapsScopesAndRoles() {
Jwt jwt = Jwt.withTokenValue("token")
.header("alg", "RS256")
.claim("scope", "orders.read orders.write")
.claim("roles", List.of("support"))
.build();
var auth = new OrderJwtAuthenticationConverter().convert(jwt);
assertThat(auth.getAuthorities()).extracting(GrantedAuthority::getAuthority)
.containsExactlyInAnyOrder("SCOPE_orders.read", "SCOPE_orders.write", "ROLE_support");
}
@Test void missingScopeGivesNoAuthorities() {
Jwt jwt = Jwt.withTokenValue("token").header("alg", "RS256").claim("sub", "u1").build();
assertThat(new OrderJwtAuthenticationConverter().convert(jwt).getAuthorities()).isEmpty(); // []
}

These tests run in milliseconds and catch the bugs that mock tests cannot: a wrong prefix, a claim read as a string when the provider sends a list, or a role that silently disappears.

5Testing @PreAuthorize on Service Methods

Method security, rules written as @PreAuthorize("hasAuthority('SCOPE_orders.write')") on a service method, is enforced by a proxy around the service bean. So we must call the method through the Spring bean, in a test that has method security enabled. @WithMockUser fills the security context with a simple user and the authorities we name.

Java
@SpringBootTest
class OrderServiceSecurityTest {
@Autowired OrderService service;
@Test @WithMockUser(authorities = "SCOPE_orders.write")
void writerCanCancel() { service.cancel(42L); } // passes
@Test @WithMockUser(authorities = "SCOPE_orders.read")
void readerCannotCancel() {
assertThatThrownBy(() -> service.cancel(42L))
.isInstanceOf(AccessDeniedException.class); // denied
}
}

When rules read the token itself, for example @PreAuthorize("#tenant == authentication.token.claims['tenant']"), a plain mock user is not enough. We then write a custom annotation, say @WithTenantJwt(tenant = "acme"), meta-annotated with @WithSecurityContext(factory = ...). Its factory builds a JwtAuthenticationToken from a real Jwt object, so every test can declare the caller in one line and the rule sees the same kind of Authentication as in production.

6One Test With a Real Signed Token

Everything so far skips the decoder, so a mistake in decoding settings, such as the wrong issuer, a missing audience check or the wrong algorithm, would pass every test. We close that gap with one integration test. We generate an RSA key pair for tests, point the resource server at the public key, for example with spring.security.oauth2.resourceserver.jwt.public-key-location in a test profile or a JwtDecoder bean built with NimbusJwtDecoder.withPublicKey, and sign tokens with the private key using NimbusJwtEncoder.

Then we send the token in an Authorization: Bearer header and check that a valid token gets 200, an expired token gets 401, and a token with the wrong issuer or audience gets 401. Notice that this test should use the same validators as production; if production adds an audience validator in a custom JwtDecoder, the test must build its decoder the same way, otherwise we are testing a different configuration. One such class is enough; the many rule tests stay fast.

7Follow-up questions

Why not just disable security in the slice tests?

Because then the tests prove nothing about authorization, which is the thing we wanted to test. With jwt() and mockJwt() we keep the real filter chain and the real rules and only replace how the caller is authenticated, so a broken rule still fails a test.

Do I need @Import of my security configuration in @WebMvcTest?

In recent Spring Boot versions, @WebMvcTest includes SecurityFilterChain beans from @Configuration classes in many setups, but behaviour has changed between versions, so check your version. Importing the security configuration explicitly makes the test independent of that detail and makes it obvious which rules are under test.

How do we test that a token for one tenant cannot read another tenant's data?

We set the tenant claim with jwt(j -> j.claim("tenant", "acme")) and request a resource owned by another tenant, expecting 403 or 404 depending on our policy. These cross-tenant negative tests are the most valuable security tests we can write, because a missing check there leaks data rather than just exposing a button.

8Conclusion

In this answer, we saw that a resource server's authorization can be tested without an identity provider by splitting the work. URL rules are tested with MockMvc's jwt() or WebTestClient's mockJwt(), always with negative cases, and with our own converter passed in when claims are mapped in a custom way. The converter itself is tested with real Jwt objects, method security with @WithMockUser or a custom @WithSecurityContext annotation, and a single integration test with a token signed by a test key proves that the decoding and validation settings match production.

What to say in the interviewAbout 80 seconds aloud

Open with

I split it into layers. For URL rules I use MockMvc with the jwt() post processor, for example jwt().authorities(new SimpleGrantedAuthority("SCOPE_orders.read")), or jwt().jwt(j -> j.claim("scope", ...)) when I want to start from claims.

Then, if they want more

That bypasses the decoder, so no identity provider is needed, but the real filter chain and rules still run. For every endpoint I write the positive case and the negative ones: wrong scope gives 403, no token gives 401. In WebFlux I do the same with WebTestClient and mutateWith(mockJwt()).

One catch is that the mock uses the default scope converter, so if we map claims ourselves I pass our converter in, and I also unit test that JwtAuthenticationConverter directly with Jwt objects from Jwt.withTokenValue, covering multiple scopes, role arrays and missing claims.

For @PreAuthorize on services I call the bean with @WithMockUser, or a custom annotation built on @WithSecurityContext when the rule reads token claims such as the tenant.

Finally I keep one integration test where I generate an RSA key, configure the decoder with the public key, sign real tokens with the private key, and check that valid, expired and wrong-issuer tokens behave correctly, because that is the only test that covers the decoding settings.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Spring Boot reference, Testing
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Your resource server validates JWTs and maps a 'scope' claim to authorities. How would...": https://scrivio-interview-library.netlify.app/spring-boot/spring-boot-test/51c0e9334e/