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

Comment From: ronodhirSoumik

At the same time, I think this should be added before authorities.add(new SimpleGrantedAuthority.... considering the current implementation [Reference User.java] Assert.isTrue(!role.startsWith("ROLE_"), () -> role + " cannot start with ROLE_ (it is automatically added)");