2017-06-21 21 views
0

時のセキュリティコンテキストを失う:春私はこのような春のブート統合テストを持ってテスト

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 
@ActiveProfiles("Test") 
@RunWith(SpringRunner.class) 
public class HelloControllerIT { 
    @Autowired 
    protected TestRestTemplate template; 

    @Test 
    public void test1() throws Exception { 
     HttpEntity request = //buildJson; 
     ResponseEntity response = template.exchange("/put", HttpMethod.PUT, request, Object.class); 
     assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED); 
    } 
} 

テンプレートは、要求を送信すると、次のようになります私のコード内のポイントがあります:

SecurityContext context = SecurityContextHolder.getContext(); 
Authentication authentication = context.getAuthentication(); 
は、

コンテキストは次のようになります。 enter image description here

匿名でないようにセキュリティコンテキストを設定する必要があります。私はこのようにそれを行うことができます。

SecurityContext context = SecurityContextHolder.createEmptyContext(); 
context.setAuthentication(authResult); 
SecurityContextHolder.setContext(context); 

しかし、私はtemplate.exchange前に、私はまだanonymousUserを得ることをやるしようとします。私はこれを試してみました:

template.withBasicAuth("User","pass"); 

それでも動作しません。 TestRestTemplateセキュリティコンテキストを設定するにはどうすればよいですか?

+0

おそらく '@ EnableWebSecurity'と' @ WithMockUser'アノテーションが必要です。 – ngreen

答えて

0

私はそれを理解しました。 WebSecurityConfigurerAdapterを実装しているクラスを作成し、そこにコンテキストを設定する必要があります。これは、私がこれをもっとETEの統合テストにすることに熱心だったあらゆる種類の嘲笑を避けることができたということでした。そのクラスがあります

public class TestSecurityConfig extends WebSecurityConfigurerAdapter { 
    @Override 
    public void configure(HttpSecurity http) throws Exception { 
     http.csrf().disable().authorizeRequests().anyRequest().permitAll().and().securityContext().securityContextRepository(new TestSecurityContextRepository()); 
    } 
} 
関連する問題