spring-projects / spring-projects/spring-security

org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers assertion issue

Open
#17,127 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

status: waiting-for-triage type: enhancement
Dominant language
Java
Stars
9.6k
Forks
6.3k
Avg merge
2d 11h
Merged PRs (30d)
52

Description

Spring Security Version: 6.4 and 6.5 and main branch on 2025/May

org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.AuthenticatedMatcher#withRoles(String... roles)

The problem: AuthenticatedMatcher#withRoles(String... roles) add to exist role prefix "ROLE_". This behavior causes the developers to modify the real roles of the corrugation.
Solution: remove prefix "ROLE_" from assertions.

Context.
Example of current behave:

User real role is: PRE_LOGIN

@Test
    void login() throws Exception {
        mockMvc.perform(formLogin(LOGIN_ENDPOINT)
                        .user("username").password("password"))
                .andDo(MockMvcResultHandlers.print())
                .andExpect(status().is2xxSuccessful())
                .andExpect(SecurityMockMvcResultMatchers.authenticated().withRoles("PRE_LOGIN"));
    }

.andExpect(SecurityMockMvcResultMatchers.authenticated().withRoles("PRE_LOGIN")) -> throw exception:

[PRE_LOGIN] does not contain the same authorities as [ROLE_PRE_LOGIN]
java.lang.AssertionError: [PRE_LOGIN] does not contain the same authorities as [ROLE_PRE_LOGIN]

For valid use of "SecurityMockMvcResultMatchers.authenticated().withRoles(…)", developer should every time does concatenate real roll with prefix "ROLE_".

Please, remove the prefix "ROLE_" in "authorities.add(new SimpleGrantedAuthority("ROLE_" + role));" 218 row

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at SecurityMockMvcResultMatchers.AuthenticatedMatcher#withRoles(String... roles), especially the authorities construction around line 218, and inspect the surrounding matcher behavior and related tests. Confirm the expected handling of an existing PRE_LOGIN authority, then update the assertion behavior and ensure the relevant tests pass without requiring a ROLE_ prefix.

Written by the indexing model from the issue text.

Assessment

Tech stack
java, spring
Domain
security, testing-qa
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.