2016-07-12 29 views
1

我一直在爲我們的Spring MVC應用程序編寫集成測試。我們使用oAuth2進行身份驗證。Java Spring MVC集成測試創建OAuth2校長

在這種情況下,Spring會給我們一個Principal實例,我們用它來確定我們必須發送回客戶端的實體。在我們的控制,我們有一個端點:

@RequestMapping("/bookings") 
public @ResponseBody ResponseEntity<List<ThirdPartyBooking>> getBookings(Principal principal) { 
    OAuth2Authentication auth = (OAuth2Authentication) principal; 
    OAuth2AuthenticationDetails authDetails = (OAuthAuthenticationDetails) auth.getDetails(); 
    // Extract stuff from the details... 
} 

現在,在我們的測試中,我想確保我們只發送預訂已認證用戶。下面的測試代碼,可以發現:

@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