3

任何人都可以提供一個代碼示例寫一個控制器的HTTPS安全控制器的集成測試?使用HTTP,我可以編寫,但使用HTTPS,我得到認證錯誤。測試彈簧控制器控制器安全與https

控制器

@RestController 
@RequestMapping("/rest/otm/v1") 
public class LoginController { 

    @Autowired 
    UserAuthenticationService userAuthService; 

    @ExceptionHandler({ AuthenticationFailedException.class}) 
    @RequestMapping(value = "/login", method = RequestMethod.POST) 
    @ResponseBody 
    public void login(HttpServletRequest request,HttpServletResponse response) throws AuthenticationDeniedException { 

     //some code 
    } 

} 

測試類

@RunWith(SpringJUnit4ClassRunner.class) 
@SpringApplicationConfiguration(classes = Application.class) 
@WebAppConfiguration 
@IntegrationTest("server.port:0") 
public class IdentityControllerTest { 

    @Value("${local.server.port}") 
    int port; 

    @Test 
    public void test_Login_Controller() { 

     SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory(); 

     Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("some-proxy", 8080)); 
     clientHttpRequestFactory.setProxy(proxy); 

     RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory); 

     HttpHeaders requestHeaders = new HttpHeaders(); 
     requestHeaders.set("credential", "pratap"); 
     requestHeaders.set("deviceid", "xyz123"); 

     HttpHeaders response = restTemplate.postForObject("https://localhost:"+port+"/rest/otm/v1/login", requestHeaders, HttpHeaders.class);    

    } 

} 

錯誤

org.springframework.web.client.ResourceAccessException: I/O error on POST request for "https://localhost:51184/rest/otm/v1/login":sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target; nested exception is javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target 
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:607) 
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:557) 
    at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:357) 
    at com.bosch.inl.otm.controller.IdentityControllerTest.test_Login_Controller(IdentityControllerTest.java:45) 

在此先感謝

回答

4

此錯誤使用自簽名證書的情況下,一般的報道。默認情況下,Java不信任它,因此您必須禁用證書驗證或將證書添加到信任存儲區。這兩種解決方案都被描述爲here

+0

感謝Guy Bouallet。 org.springframework.web.client.ResourceAccessException:對「https:// localhost:53474/rest/otm/v1/login」的POST請求發生I/O錯誤:嘗試解決此問題,但獲得ResourceAccessException :意外的結束文件從服務器;嵌套異常是java.net.SocketException:服務器上的文件意外結束 –

+0

您選擇了哪種解決方案? –

+0

對不起,這是我的錯誤。它的工作是禁用SSL驗證。 有什麼方法可以通過驗證證書來測試嗎? –