2

I've been trying to write an integration test for our Spring MVC application. We're using oAuth2 for authentication.

Spring in this case gives us a Principal instance which we use to determine which entities we have to send back to the client. In our controller we have an endpoint:

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

Now in our test I want to make sure that we only send bookings for the authenticated user. Below the code for the test can be found:

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

How would I insert a OAuth2Authentication at the ????

4

1 回答 1

3

我使用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 ) )
于 2016-07-12T11:51:11.353 回答