简体   繁体   中英

Java Spring MVC integration test create OAuth2 Principal

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 ??? ?

I use RequestPostProcessor for test authentication. Just add stub token to request:

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

And use it in tests:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM