在 oAuth2 资源服务器应用程序中使用@WithMockUser(与@SpringBootTest)
Use @WithMockUser (with @SpringBootTest) inside an oAuth2 Resource Server Application
环境:
我有一个基于 spring 启动的微服务架构应用程序,由多个基础设施服务和资源服务(包含业务逻辑)组成。授权和身份验证由管理用户实体并为客户端创建 JWT 令牌的 oAuth2-Service 处理。
为了完整地测试单个微服务应用程序,我尝试使用 testNG、spring.boot.test、org.springframework.security.test ...
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, properties = {"spring.cloud.discovery.enabled=false", "spring.cloud.config.enabled=false", "spring.profiles.active=test"})
@AutoConfigureMockMvc
@Test
public class ArtistControllerTest extends AbstractTestNGSpringContextTests {
@Autowired
private MockMvc mvc;
@BeforeClass
@Transactional
public void setUp() {
// nothing to do
}
@AfterClass
@Transactional
public void tearDown() {
// nothing to do here
}
@Test
@WithMockUser(authorities = {"READ", "WRITE"})
public void getAllTest() throws Exception {
// EXPECT HTTP STATUS 200
// BUT GET 401
this.mvc.perform(get("/")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
}
}
安全(资源服务器)配置如下
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
// get the configured token store
@Autowired
TokenStore tokenStore;
// get the configured token converter
@Autowired
JwtAccessTokenConverter tokenConverter;
/**
* !!! configuration of springs http security !!!
*/
@Override
public void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/**").authenticated();
}
/**
* configuration of springs resource server security
*/
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
// set the configured tokenStore to this resourceServer
resources.resourceId("artist").tokenStore(tokenStore);
}
}
以及控制器内部注释的以下基于安全检查的方法class
@PreAuthorize("hasAuthority('READ')")
@RequestMapping(value = "/", method = RequestMethod.GET)
public List<Foo> getAll(Principal user) {
List<Foo> foos = fooRepository.findAll();
return foos;
}
我认为这会起作用,但是当 运行 测试时我只得到一个断言错误
java.lang.AssertionError: Status
Expected :200
Actual :401
问题:
有什么完全明显的我做错了吗?还是 @WithMockUser 不会在 oAuth2 环境中与 @SpringBootTest 和 @AutoConfigureMockMvc 一起工作?如果是这种情况...作为此类(集成)测试的一部分,测试基于路由和方法的安全配置的最佳方法是什么?
附录:
我也尝试了不同的方法,如下所示......但它导致了相同的结果:(
this.mvc.perform(get("/")
.with(user("admin").roles("READ","WRITE").authorities(() -> "READ", () -> "WRITE"))
.accept(MediaType.APPLICATION_JSON))
我遇到了同样的问题,我发现的唯一方法是创建一个令牌并在 mockMvc 执行中使用它
mockMvc.perform(get("/resource")
.with(oAuthHelper.bearerToken("test"))
以及 OAuthHelper:
@Component
@EnableAuthorizationServer
public class OAuthHelper extends AuthorizationServerConfigurerAdapter {
@Autowired
AuthorizationServerTokenServices tokenservice;
@Autowired
ClientDetailsService clientDetailsService;
public RequestPostProcessor bearerToken(final String clientid) {
return mockRequest -> {
OAuth2AccessToken token = createAccessToken(clientid);
mockRequest.addHeader("Authorization", "Bearer " + token.getValue());
return mockRequest;
};
}
OAuth2AccessToken createAccessToken(final String clientId) {
ClientDetails client = clientDetailsService.loadClientByClientId(clientId);
Collection<GrantedAuthority> authorities = client.getAuthorities();
Set<String> resourceIds = client.getResourceIds();
Set<String> scopes = client.getScope();
Map<String, String> requestParameters = Collections.emptyMap();
boolean approved = true;
String redirectUrl = null;
Set<String> responseTypes = Collections.emptySet();
Map<String, Serializable> extensionProperties = Collections.emptyMap();
OAuth2Request oAuth2Request = new OAuth2Request(requestParameters, clientId, authorities,
approved, scopes, resourceIds, redirectUrl, responseTypes, extensionProperties);
User userPrincipal = new User("user", "", true, true, true, true, authorities);
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(userPrincipal, null, authorities);
OAuth2Authentication auth = new OAuth2Authentication(oAuth2Request, authenticationToken);
return tokenservice.createAccessToken(auth);
}
@Override
public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("test")
.authorities("READ");
}
}
@WithMockUser
在 SecurityContext 中创建身份验证。
同样适用于 with(user("username"))
.
默认情况下,OAuth2AuthenticationProcessingFilter 不使用 SecurityContext,但始终从令牌 ("stateless") 构建身份验证。
您可以轻松更改此行为,将资源服务器安全配置中的无状态标志设置为 false:
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration implements ResourceServerConfigurer {
@Override
public void configure(ResourceServerSecurityConfigurer security) throws Exception {
security.stateless(false);
}
@Override
public void configure(HttpSecurity http) {}
}
另一种选择是扩展 ResourceServerConfigurerAdapter,但问题在于它带有强制对所有请求进行身份验证的配置。除了无状态之外,实现该接口会使您的主要安全配置保持不变。
当然,仅在您的测试上下文中将标志设置为 false。
因为我专门尝试针对我们的 ResourceServerConfiguration 编写测试,所以我通过为它创建一个测试包装器来解决这个问题,该包装器将 security.stateless 设置为 false:
@Configuration
@EnableResourceServer
public class ResourceServerTestConfiguration extends ResourceServerConfigurerAdapter {
private ResourceServerConfiguration configuration;
public ResourceServerTestConfiguration(ResourceServerConfiguration configuration) {
this.configuration = configuration;
}
@Override
public void configure(ResourceServerSecurityConfigurer security) throws Exception {
configuration.configure(security);
security.stateless(false);
}
@Override
public void configure(HttpSecurity http) throws Exception {
configuration.configure(http);
}
}
环境: 我有一个基于 spring 启动的微服务架构应用程序,由多个基础设施服务和资源服务(包含业务逻辑)组成。授权和身份验证由管理用户实体并为客户端创建 JWT 令牌的 oAuth2-Service 处理。
为了完整地测试单个微服务应用程序,我尝试使用 testNG、spring.boot.test、org.springframework.security.test ...
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, properties = {"spring.cloud.discovery.enabled=false", "spring.cloud.config.enabled=false", "spring.profiles.active=test"})
@AutoConfigureMockMvc
@Test
public class ArtistControllerTest extends AbstractTestNGSpringContextTests {
@Autowired
private MockMvc mvc;
@BeforeClass
@Transactional
public void setUp() {
// nothing to do
}
@AfterClass
@Transactional
public void tearDown() {
// nothing to do here
}
@Test
@WithMockUser(authorities = {"READ", "WRITE"})
public void getAllTest() throws Exception {
// EXPECT HTTP STATUS 200
// BUT GET 401
this.mvc.perform(get("/")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
}
}
安全(资源服务器)配置如下
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
// get the configured token store
@Autowired
TokenStore tokenStore;
// get the configured token converter
@Autowired
JwtAccessTokenConverter tokenConverter;
/**
* !!! configuration of springs http security !!!
*/
@Override
public void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/**").authenticated();
}
/**
* configuration of springs resource server security
*/
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
// set the configured tokenStore to this resourceServer
resources.resourceId("artist").tokenStore(tokenStore);
}
}
以及控制器内部注释的以下基于安全检查的方法class
@PreAuthorize("hasAuthority('READ')")
@RequestMapping(value = "/", method = RequestMethod.GET)
public List<Foo> getAll(Principal user) {
List<Foo> foos = fooRepository.findAll();
return foos;
}
我认为这会起作用,但是当 运行 测试时我只得到一个断言错误
java.lang.AssertionError: Status
Expected :200
Actual :401
问题:
有什么完全明显的我做错了吗?还是 @WithMockUser 不会在 oAuth2 环境中与 @SpringBootTest 和 @AutoConfigureMockMvc 一起工作?如果是这种情况...作为此类(集成)测试的一部分,测试基于路由和方法的安全配置的最佳方法是什么?
附录:
我也尝试了不同的方法,如下所示......但它导致了相同的结果:(
this.mvc.perform(get("/")
.with(user("admin").roles("READ","WRITE").authorities(() -> "READ", () -> "WRITE"))
.accept(MediaType.APPLICATION_JSON))
我遇到了同样的问题,我发现的唯一方法是创建一个令牌并在 mockMvc 执行中使用它
mockMvc.perform(get("/resource")
.with(oAuthHelper.bearerToken("test"))
以及 OAuthHelper:
@Component
@EnableAuthorizationServer
public class OAuthHelper extends AuthorizationServerConfigurerAdapter {
@Autowired
AuthorizationServerTokenServices tokenservice;
@Autowired
ClientDetailsService clientDetailsService;
public RequestPostProcessor bearerToken(final String clientid) {
return mockRequest -> {
OAuth2AccessToken token = createAccessToken(clientid);
mockRequest.addHeader("Authorization", "Bearer " + token.getValue());
return mockRequest;
};
}
OAuth2AccessToken createAccessToken(final String clientId) {
ClientDetails client = clientDetailsService.loadClientByClientId(clientId);
Collection<GrantedAuthority> authorities = client.getAuthorities();
Set<String> resourceIds = client.getResourceIds();
Set<String> scopes = client.getScope();
Map<String, String> requestParameters = Collections.emptyMap();
boolean approved = true;
String redirectUrl = null;
Set<String> responseTypes = Collections.emptySet();
Map<String, Serializable> extensionProperties = Collections.emptyMap();
OAuth2Request oAuth2Request = new OAuth2Request(requestParameters, clientId, authorities,
approved, scopes, resourceIds, redirectUrl, responseTypes, extensionProperties);
User userPrincipal = new User("user", "", true, true, true, true, authorities);
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(userPrincipal, null, authorities);
OAuth2Authentication auth = new OAuth2Authentication(oAuth2Request, authenticationToken);
return tokenservice.createAccessToken(auth);
}
@Override
public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("test")
.authorities("READ");
}
}
@WithMockUser
在 SecurityContext 中创建身份验证。
同样适用于 with(user("username"))
.
默认情况下,OAuth2AuthenticationProcessingFilter 不使用 SecurityContext,但始终从令牌 ("stateless") 构建身份验证。
您可以轻松更改此行为,将资源服务器安全配置中的无状态标志设置为 false:
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration implements ResourceServerConfigurer {
@Override
public void configure(ResourceServerSecurityConfigurer security) throws Exception {
security.stateless(false);
}
@Override
public void configure(HttpSecurity http) {}
}
另一种选择是扩展 ResourceServerConfigurerAdapter,但问题在于它带有强制对所有请求进行身份验证的配置。除了无状态之外,实现该接口会使您的主要安全配置保持不变。
当然,仅在您的测试上下文中将标志设置为 false。
因为我专门尝试针对我们的 ResourceServerConfiguration 编写测试,所以我通过为它创建一个测试包装器来解决这个问题,该包装器将 security.stateless 设置为 false:
@Configuration
@EnableResourceServer
public class ResourceServerTestConfiguration extends ResourceServerConfigurerAdapter {
private ResourceServerConfiguration configuration;
public ResourceServerTestConfiguration(ResourceServerConfiguration configuration) {
this.configuration = configuration;
}
@Override
public void configure(ResourceServerSecurityConfigurer security) throws Exception {
configuration.configure(security);
security.stateless(false);
}
@Override
public void configure(HttpSecurity http) throws Exception {
configuration.configure(http);
}
}