2016-07-12 30 views
1

私はSpring MVCアプリケーションの統合テストを作成しようとしています。認証にoAuth2を使用しています。Java Spring MVC統合テスト作成OAuth2プリンシパル

この場合、Springはクライアントに返す必要のあるエンティティを特定するために使用するPrincipalインスタンスを返します。私たちのコントローラにはエンドポイントがあります:

私たちのテストでは、認証されたユーザーにのみ予約を送信していることを確認します。テスト用のコードの下に見つけることができます:

@RunWith(SpringJUnit4ClassRunner.class) 
@SpringApplicationConfiguration(classes = {ThirdPartyBookingServiceConfiguration.class}) 
@WebAppConfiguration 
@Component 
public abstract class RepositoryTestBase { 
    @Resource 
    private WebApplicationContext context; 
    private MockMvc mockMvc; 

    @Before 
    public void setUp() { 
     mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); 
    } 

    @Test 
    public void shouldOnlyReturnUserBookings() throws Exception { 
     MockHttpServletResponse result = mockMvc.perform(MockMvcRequestBuilders.get("/bookings").principal(???)).andReturn().getResponse(); 
     // Validate the response 
    } 
} 

私は???OAuth2Authenticationを挿入する方法は?

答えて

1

私はRequestPostProcessorをテスト認証に使用します。ただ、リクエストにスタブトークンを追加します。

@Component 
public class OAuthHelper { 

    @Autowired 
    AuthorizationServerTokenServices tokenservice; 

    public RequestPostProcessor addBearerToken(final String username, String... authorities) 
    { 
     return mockRequest -> { 
      OAuth2Request oauth2Request = new OAuth2Request(null, "client-id", 
         null, true, null, null, null, null, null); 
      Authentication userauth = new TestingAuthenticationToken(username, null, authorities); 
      OAuth2Authentication oauth2auth = new OAuth2Authentication(oauth2Request, userauth); 
      OAuth2AccessToken token = tokenservice.createAccessToken(oauth2auth); 

      mockRequest.addHeader("Authorization", "Bearer " + token.getValue()); 
      return mockRequest; 
     }; 
    } 
} 

やテストでそれを使用します。

accessToken = authHelper.addBearerToken(TEST_USER, TEST_ROLE); 
    mockMvc.perform(get("/cats").with(accessToken)) 
+0

これは私が探していたまさにありませんでした。それは大いに役立った。ありがとう! – irundaia

関連する問題