在oAuth2资源服务器应用程序中使用@WithMockUser(带有@SpringBootTest) [英] Use @WithMockUser (with @SpringBootTest) inside an oAuth2 Resource Server Application

查看:2309
本文介绍了在oAuth2资源服务器应用程序中使用@WithMockUser(带有@SpringBootTest)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

环境
我有一个基于Spring Boot的微服务架构应用程序,包含多个基础架构服务和资源服务(包含业务逻辑)。授权和身份验证由管理用户实体和为客户端创建JWT令牌的oAuth2-Service处理。

Environment: I have a spring boot based microservice architecture application consisting of multiple infrastructural services and resource services (containing the business logic). Authorization and authentication is handled by an oAuth2-Service managing the user entities and creating JWT tokens for the clients.

要完整地测试单个微服务应用程序,我尝试构建使用 testNG 进行测试, spring.boot.test org.springframework.security.test ...

To test a single microservice application in its entirety i tried to build tests with 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())
  }
}

其中安全(资源服务器)配置如下

where the security (resource server) config is the following

@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);
  }

}

以及基于以下方法的安全检查在控制器类内注释

and the following method based security check annotated inside the controller class

@PreAuthorize("hasAuthority('READ')")
@RequestMapping(value = "/", method = RequestMethod.GET)
public List<Foo> getAll(Principal user) {
    List<Foo> foos = fooRepository.findAll();
    return foos;
}

我认为这样可行但运行测试时我只得到一个断言错误

I thought that would work but when running the test i only get an assertion error

java.lang.AssertionError: Status 
Expected :200
Actual   :401



问题
是否有一些非常明显的东西我做错了?或者@WithMockUser是否不能在oAuth2环境中使用@SpringBootTest和@AutoConfigureMockMvc?如果是这种情况......作为这样的(集成)测试的一部分,测试基于路由和方法的安全配置的最佳方法是什么?


Question: Is there something totally obvious that i am doing wrong? Or is @WithMockUser not going to work with @SpringBootTest and @AutoConfigureMockMvc in an oAuth2 environment? If this is the case... what would be the best approach for testing route and method based security configurations as part of such an (integration) test like this one?



附录
我也尝试了不同的方法,如下所示...但它导致了相同的结果:(


Appendix: I also tried different approaches like something like the following... but it led to the same result :(

this.mvc.perform(get("/")
        .with(user("admin").roles("READ","WRITE").authorities(() -> "READ", () -> "WRITE"))
        .accept(MediaType.APPLICATION_JSON))

参见

春季安全测试

spring boot 1.4 testing

推荐答案

@WithMockUser 中创建身份验证SecurityContext的
同样适用于 with(user(username))

默认情况下 OAuth2AuthenticationProcessingFilter 不使用SecurityContext,但总是从令牌构建身份验证(无状态)。

By default the OAuth2AuthenticationProcessingFilter does not use the SecurityContext, but always build the authentication from the token ("stateless").

您可以轻松更改此行为设置资源服务器安全配置中的无状态标志为false:

You can easily change this behavior be setting the stateless flag in the resource server security configuration to false:

@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(ResourceServerSecurityConfigurer security) throws Exception {
        security.stateless(false);
    }
}

当然,将标志设置为仅在测试环境中使用false

这篇关于在oAuth2资源服务器应用程序中使用@WithMockUser(带有@SpringBootTest)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆