Search code examples
spring-bootx509mockmvcspring-restdocsp12

Spring REST Docs - Add p12 certificate in Curl Snippet


I am using MockMVC and Spring REST docs and am trying to generate a curl snippet that has the certificate in it. I imagine the certificate portion of the curl statement should look something like:

--cert-type P12 --cert <cert-file-here.p12>:<password>

I have tried using the test below to generate the curl request.

@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD, hierarchyMode = DirtiesContext.HierarchyMode.CURRENT_LEVEL)
@ExtendWith({RestDocumentationExtension.class, SpringExtension.class})
@SpringBootTest
public class LoginTest {
    private MockMvc mockMvc;
    private X509Certificate certificate;
    
    
    
    @BeforeEach
    public void setUp(WebApplicationContext webApplicationContext,
      RestDocumentationContextProvider restDocumentation) throws KeyStoreException, NoSuchAlgorithmException, 
                                                                CertificateException, IOException {

        this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
                                      .apply(documentationConfiguration(restDocumentation))
                                      .addFilters(sessionRepositoryFilter)
                                      .apply(springSecurity())
    
                                      .build();

        certificate = ControllerUtil.getCertificate();
    }
    
    @Test
    public void loginTest() throws Exception {
        
   
        
        mockMvc.perform(post("/login")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .with(x509(certificate))
                .param("username", "username")
                .param("password", "password")
        )
       .andDo(print()).andDo(document("login"));
        



    }
}



With this test the following curl request is generated:

curl 'http://localhost:8080/login' -i -X POST \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'username=username&password=password'

I am expecting the generated curl request to look something like:

curl 'http://localhost:8080/login' -i -X POST \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'username=username&password=password' \
--cert-type P12 --cert localhost.p12:password

Is there a way to add the certificate portion of the command to the curl request snippet?


Solution

  • I don't think there is a way to do this programmatically.

    What I ended up doing was manually edit the curl snippets in target/generated-snippets and then generate the documentation.

    This is the correct curl statement I was looking for.

    curl --cert-type P12 --cert certName.p12:certificatePassword "http://localhost:8080/login" -i -X POST -H "Content-Type: application/x-www-formurlencoded"
    -d "username=username&password=password"