对于最新的稳定版本,请使用 Spring Security 6.4.3spring-doc.cadn.net.cn

SecurityMockMvcResultMatchers

有时,需要对请求进行各种与安全相关的断言。 为了满足这一需求,Spring Security Test 支持实现了 Spring MVC Test 的ResultMatcher接口。 为了使用 Spring Security 的ResultMatcherimplementations 确保使用以下 static import:spring-doc.cadn.net.cn

import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.*;
import org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.*

Unauthenticated Assertion

At times it may be valuable to assert that there is no authenticated user associated with the result of a MockMvc invocation. For example, you might want to test submitting an invalid username and password and verify that no user is authenticated. You can easily do this with Spring Security’s testing support using something like the following:spring-doc.cadn.net.cn

mvc
	.perform(formLogin().password("invalid"))
	.andExpect(unauthenticated());
mvc
    .perform(formLogin().password("invalid"))
    .andExpect { unauthenticated() }

Authenticated Assertion

It is often times that we must assert that an authenticated user exists. For example, we may want to verify that we authenticated successfully. We could verify that a form based login was successful with the following snippet of code:spring-doc.cadn.net.cn

mvc
	.perform(formLogin())
	.andExpect(authenticated());
mvc
    .perform(formLogin())
    .andExpect { authenticated() }

If we wanted to assert the roles of the user, we could refine our previous code as shown below:spring-doc.cadn.net.cn

mvc
	.perform(formLogin().user("admin"))
	.andExpect(authenticated().withRoles("USER","ADMIN"));
mvc
    .perform(formLogin())
    .andExpect { authenticated().withRoles("USER","ADMIN") }

Alternatively, we could verify the username:spring-doc.cadn.net.cn

mvc
	.perform(formLogin().user("admin"))
	.andExpect(authenticated().withUsername("admin"));
mvc
    .perform(formLogin().user("admin"))
    .andExpect { authenticated().withUsername("admin") }

We can also combine the assertions:spring-doc.cadn.net.cn

mvc
	.perform(formLogin().user("admin"))
	.andExpect(authenticated().withUsername("admin").withRoles("USER", "ADMIN"));
mvc
    .perform(formLogin().user("admin"))
    .andExpect { authenticated().withUsername("admin").withRoles("USER", "ADMIN") }

We can also make arbitrary assertions on the authenticationspring-doc.cadn.net.cn

mvc
	.perform(formLogin())
	.andExpect(authenticated().withAuthentication(auth ->
		assertThat(auth).isInstanceOf(UsernamePasswordAuthenticationToken.class)));
mvc
    .perform(formLogin())
    .andExpect {
        authenticated().withAuthentication { auth ->
            assertThat(auth).isInstanceOf(UsernamePasswordAuthenticationToken::class.java) }
        }
    }