Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocked Server for Spring Oauth endpoint

I'm trying to do an integration test to see what the behavior is like when my Registration Endpoint fails. My Registration endpoint is an API provided by an external source (which is secured by Spring OAuth). The client website is using the client side Spring Oauth to communicate with the API.

What I'm trying to do is mocked the API however, I am getting issues where the request is not going against the mocked endpoints; org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://localhost:8081/oauth/token":Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect. Here's my test below:

 @WebAppConfiguration
 @RunWith(SpringJUnit4ClassRunner.class)
 @ContextConfiguration(locations = {"classpath*:RegistrationControllerIntegrationTest-context.xml"})
 public class RegistrationControllerIntegrationTest {


  @Resource
  RegistrationController registrationController;

  @Resource
  private WebApplicationContext webApplicationContext;

  MockMvc mockMvc;

  @Value("${oauth.accessTokenUri}")
  private String oauthUri;

  private MockRestServiceServer mockRestServiceServer;


  private OAuth2RestTemplate clientCredRest;


  @Resource(name = "clientCredentialRest")
  public void setClientCredRest(OAuth2RestTemplate clientCredRest) {
    this.clientCredRest = clientCredRest;
  }



  @Before
  public void setUp()
  {
    this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();

    this.mockRestServiceServer = MockRestServiceServer.createServer(this.clientCredRest);


  }
  @Test
  public void testRegistrationThatReturnsBadRequestWhenUserAlreadyExist()
  {




 this.mockRestServiceServer.expect(MockRestRequestMatchers.requestTo("localhost:8081/oauth/token")).andExpect(MockRestRequestMatchers.method(HttpMethod.POST))
    .andRespond(MockRestResponseCreators.withSuccess().contentType(MediaType.APPLICATION_JSON).body("{\n" +
            "\"access_token\": \"8ecd93d4-2484-46de-922a-652fa79d027d\",\n" +
            "\"token_type\": \"bearer\",\n" +
            "\"expires_in\": 1265\n" +
            "\"scope\": \"read write\"\n" +
            "}"));

      Gson gson = Converters.registerDateTime(new GsonBuilder()).create();
      PodamFactory factory = new PodamFactoryImpl();
      RegistrationDTO dto = factory.manufacturePojo(RegistrationDTO.class);
    dto.setUserName("test");
      String json = gson.toJson(dto);


         this.mockRestServiceServer.expect(MockRestRequestMatchers.requestTo("localhost:8081/public/registration")).andExpect(MockRestRequestMatchers.method(HttpMethod.POST))
            .andRespond(MockRestResponseCreators.withBadRequest().contentType(MediaType.APPLICATION_JSON).body("{\n" +
                    "resource: null\n" +
                    "field: \"user_name\"\n" +
                    "code: \"0\"\n" +
                    "message: \"Username already exist\"\n" +
                    "}"));

      MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/frontend/register").content(json).header("activate", "true").header("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36").header("Origin","chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo").contentType(MediaType.APPLICATION_JSON);

      try {
             this.mockMvc.perform(requestBuilder).andExpect(MockMvcResultMatchers.status().isBadRequest());
      } catch (Exception e) {
          e.printStackTrace();
      }
   }
 }

Note, the reason I setup the two expectation for the mocked web server is due to how Spring Oauth gets an access token before making the request to public/registration endpoint. Let me know if I'm missing anything.

Thanks.

like image 962
Dean Avatar asked Oct 06 '15 17:10

Dean


People also ask

Why is spring OAuth deprecated?

Since Spring Security doesn't provide Authorization Server support, migrating a Spring Security OAuth Authorization Server is out of scope for this document.

What is OAuth 2.0 and how it works in spring boot?

OAuth2 is an authorization framework that enables the application Web Security to access the resources from the client. To build an OAuth2 application, we need to focus on the Grant Type (Authorization code), Client ID and Client secret.


1 Answers

Setting the accesstoken myself worked for me, this prevents the OAuth2RestTemplate from getting the accesstoken itself:

@Before
public void before() {
    mockServer = MockRestServiceServer.createServer(oAuth2RestTemplate);
    oAuth2RestTemplate.getOAuth2ClientContext().setAccessToken(
            new DefaultOAuth2AccessToken("accesstoken")
    );
}
like image 123
BRNTZN Avatar answered Oct 14 '22 06:10

BRNTZN