Phil Palmiero
Phil Palmiero

Reputation: 51

Need help testing a REST controller that requires oauth2

I am following this example for how to test my REST controller with oauth2. Testing an OAuth Secured API with Spring MVC

The code that I am stuck on is this line .with(httpBasic("fooClientIdPassword","secret")) Does anyone know where is httpBasic method coming from? How is it instantiated, etc.? Thank you.

private String obtainAccessToken(String username, String password) throws Exception {

    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("grant_type", "password");
    params.add("client_id", "fooClientIdPassword");
    params.add("username", username);
    params.add("password", password);

    ResultActions result 
      = mockMvc.perform(post("/oauth/token")
               .params(params)
               .with(httpBasic("fooClientIdPassword","secret"))
               .accept("application/json;charset=UTF-8"))
               .andExpect(status().isOk())
               .andExpect(content().contentType("application/json;charset=UTF-8"));

    String resultString = result.andReturn().getResponse().getContentAsString();

    JacksonJsonParser jsonParser = new JacksonJsonParser();
    return jsonParser.parseMap(resultString).get("access_token").toString();
}

Upvotes: 0

Views: 227

Answers (1)

FrancescoM
FrancescoM

Reputation: 1400

The httpBasic method comes from SecurityMockMvcRequestPostProcessors

I suppose you cannot find it cause you have not imported the dependency in your project. Once you add

<dependency>
  <groupId>org.springframework.security</groupId>
  <artifactId>spring-security-test</artifactId>
  <scope>test</scope>
</dependency>

in your pom you will be able to import and use it.

Upvotes: 2

Related Questions