在 oAuth2 资源服务器应用程序中使用@WithMockUser(带@SpringBootTest)

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

为了完整地测试单个微服务应用程序,我试图使用testNGspring.boot.testorg.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);
  }

}

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

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

详见
弹簧安全测试
弹簧开机1.4测试


答案 1

@WithMockUserSecurityContext 中创建身份验证。这同样适用于 .with(user("username"))

默认情况下,OAuth2AuthenticationProcessingFilter 不使用 SecurityContext,但始终从令牌生成身份验证(“无状态”)。

您可以轻松地将此行为更改为将资源服务器安全配置中的无状态标志设置为 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


答案 2

我有同样的问题,我发现的唯一方法是创建一个令牌并在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");
    }

}

推荐