0

This is my client code:

@GetMapping("/")
    public String home() throws NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, KeyStoreException, KeyManagementException, UnrecoverableKeyException, RestClientException, URISyntaxException {

        String url = "https://localhost:8483/secure-server/hola";
//        
//        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
//        
//        keyStore.load(new FileInputStream(new File("client-keystore.jks")), "secret".toCharArray());
//
//        System.out.println(url);
//        SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
//                new SSLContextBuilder()
//                        .loadTrustMaterial(null, new TrustSelfSignedStrategy())
//                        .loadKeyMaterial(keyStore, "secret".toCharArray())
//                        .build(),
//                NoopHostnameVerifier.INSTANCE);
//
//        HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
//
//        ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
//        RestTemplate restTemplate = new RestTemplate(requestFactory);
//        String record = restTemplate.getForObject(url, String.class);
////        
//

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<String> request = new HttpEntity<>("", headers);

        return restTemplate.exchange(url, HttpMethod.POST, request , String.class ).getBody();

//
//        ResponseEntity<String> resp = restTemplate.exchange(
//                new URI(url), HttpMethod.GET, 
//                httpEntity, String.class);

        //return model.getBody();


    }

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) throws Exception {
        char[] password = "secret".toCharArray();

        SSLContext sslContext = SSLContextBuilder.create()
                .loadKeyMaterial(keyStore("client-keystore.jks", password), password)
                .loadTrustMaterial(new File("client-truststore.jks"),"secret".toCharArray()).build();

        HttpClient client = HttpClients.custom().setSSLContext(sslContext).build();
        return builder
                .requestFactory(new HttpComponentsClientHttpRequestFactory(client))
                .build();
    }

     private KeyStore keyStore(String file, char[] password) throws Exception {
        KeyStore keyStore = KeyStore.getInstance("jks");
        File key = ResourceUtils.getFile(file);
        try (InputStream in = new FileInputStream(key)) {
            keyStore.load(in, password);
        }
        return keyStore;
    }

This is my server code with the two methods post and get, the get is working but post is not working:

@RestController
public class HomeRestController {
   @PostMapping("/hola")
   public String home(Principal principal) {
      return String.format("Hello %s!", principal.getName());
   }

   @GetMapping("/holaa")
   public String homee(Principal principal) {
      return String.format("Hello %s!", principal.getName());
  }
}

I have this is my YML with the mutual authentication configuration:

server:
  context-path: /${spring.application.name}
  port: 8483
  ssl:
    key-store: server-keystore.keystore
    key-store-password: pass123
    key-alias: default
    trust-store: server-truststore.jks
    trust-store-password: secret
    enabled: true
    client-auth: need

Calling the getMaping it works, but calling the postMaping it returns to me 403.

The keystore and trustore are configured and are OK.

And in my security configuration I have:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated().and().x509()
                .subjectPrincipalRegex("CN=(.*?)(?:,|$)").userDetailsService(userDetailsService());
    }

    @Override
    @Bean
    public UserDetailsService userDetailsService() {
        return (username -> {

                return new User(username, "",
                        AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"));

        });
    }
}

Why my post calling does not work?

Code Geas Coder
  • 1,839
  • 4
  • 23
  • 29
  • Let me guess, you have Spring Security as a dependency in your server and haven’t taken the time to configure it properly... By default CSRF protection is enabled if you don’t pass the token and aren’t authenticated you will get a 403. – M. Deinum Jan 08 '19 at 19:03
  • Yes, I have added my spring security configuration with the new user – Code Geas Coder Jan 08 '19 at 21:03
  • And I tryed with: http.csrf().disable().authorizeRequests().antMatchers("/*").hasRole("ADMIN") – Code Geas Coder Jan 08 '19 at 21:18
  • Your user has role user not admin. Also have you properly configured the certificates on the server side? – M. Deinum Jan 09 '19 at 06:52
  • Yes in my server side I have the trustore and keystore well. My trustore has my client cert. and I export my keystore cert to client trustore – Code Geas Coder Jan 09 '19 at 16:28

0 Answers0