Home » Java » java – Spring security – Enable HTTPS – client gets 403 unauthorized-Exceptionshub

java – Spring security – Enable HTTPS – client gets 403 unauthorized-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m trying to create a demo app using spring security, I need to protect my Rest API with SSL certificate.
These are the steps I did to create the example:
1- Generated a JKS file using keytool command:

keytool -genkey -keyalg RSA -alias tomcat -keystore selfsigned.jks -validity 365 -keysize 2048

2- Converted the resulted jks to pkcs12 format:

keytool -genkey -keyalg RSA -alias tomcat -keystore selfsigned.jks -validity 365 -keysize 2048

3- Created a server-side application as follow:

@EnableWebSecurity
public class X509AuthenticationServer extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .x509()
                .subjectPrincipalRegex("OU=My self signed certificate");
    }

}

@Controller
@RequestMapping("/get")
public class UserController {
    @PostMapping(value = "/user")
    public String user(@RequestBody UserInfo userInfo) {

        return "Welcome: " + userInfo.getUsername();
    }
}


server.ssl.key-store=/Users/mymacuser/devhome/certpoc/selfsigned.jks
server.ssl.key-store-password=marwan
server.ssl.key-alias=tomcat
server.ssl.key-password=marwan
server.ssl.enabled=true
server.port=8443
spring.security.user.name=Admin
spring.security.user.password=admin
spring.security.require-ssl=true

4- Created a client-side application as following:

@Configuration
public class BeanConfig {

    @Bean("httpsClient")
    public RestTemplate getSSLRestTemplate() throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {
        char[] storePassword = "marwan".toCharArray();
        File keyStore =  new File("/Users/mymacuser/devhome/certpoc/selfsigned.jks");

        SSLContext sslContext = new SSLContextBuilder()
                .loadTrustMaterial(keyStore, storePassword)
                .loadKeyMaterial(keyStore, storePassword, storePassword)
                .build();

        SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

        CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(client);
        RestTemplate restTemplate = new RestTemplate(factory);
        // restTemplate.setMessageConverters(List.of(new Jaxb2RootElementHttpMessageConverter()));
        return restTemplate;
    }

@RestController
@RequestMapping("/get")
public class ClientController {

    @Autowired
    @Qualifier("httpsClient")
    private RestTemplate httpsClient;


    @RequestMapping("/user")
    public String getUserFromServer() throws URISyntaxException {

        ResponseEntity<String> s = httpsClient.exchange("https://localhost:8443/get/user", HttpMethod.POST, new HttpEntity<UserInfo>(new UserInfo("marwan")), String.class);
        return s.getBody();

    }
}

As you can notice, My client-side is a (MITM) man in the middle service that I call from a POSTMAN or curl request.

When I invoke my request to the MITM service, I get as a response:

{
    "timestamp": "2020-02-17T09:16:20.399+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "403 : [{\"timestamp\":\"2020-02-17T09:16:20.325+0000\",\"status\":403,\"error\":\"Forbidden\",\"message\":\"Forbidden\",\"path\":\"/get/user\"}]",
    "path": "/get/user"
}

I tried printing the network logs for both MITM and server-side, and both show they are exchanging the correct certificate

How to&Answers:

Ok,
So I solved this issue, And here is the solution in case someone is interested:
In TLS there are two different stores:
KeyStore – Used to store keys to be used to seld identification against the other peer
TrustStore – User to tore keys of trusted peers
For server-side authentication, it’s needed to specify the trust store as well and to include the client cert.
Also, it’s needed to add the following property to the application.properties file:

server.ssl.client-auth=need

So the application.proprties should include:

server.ssl.trust-store=file:/Users/mymacuser/devhome/certpoc/trust.jks
server.ssl.trust-store-type=JKS
server.ssl.trust-store-password=marwan
server.ssl.client-auth=need