1

I am using Spring WebClient to hit a Rest Service which requires NTLM Authentication. It works in Postman like below:

  1. Hit the URL - http://example.com:83/api/auth/token with authentication as NTLM authentication and provide the user name and password. When hitting this service, it returns a token.
  2. This token has to be passed in header as bearer token for the actual post service - http://example.com:89/api/v1/employee

But when I tried the same using Spring WebClient, I am facing 401 - Unauthorized error. Below the code snippet I am using.

BasicCredentialsProvider tokenProvider = new BasicCredentialsProvider();
    tokenProvider.setCredentials(
        new AuthScope("http", "example.com", 83, "/api/auth/token", StandardAuthScheme.NTLM),
        new NTCredentials("testuser", "pwd".toCharArray(), null, null)
    );
    webClient = WebClient.builder()
        .clientConnector(new HttpComponentsClientHttpConnector
            (HttpAsyncClients
                .custom()
                .setDefaultCredentialsProvider(tokenProvider)
                .setTargetAuthenticationStrategy(DefaultAuthenticationStrategy.INSTANCE)
                .setDefaultRequestConfig(
                    RequestConfig.custom()
                        .setAuthenticationEnabled(true)
               .setTargetPreferredAuthSchemes(Collections.singletonList(StandardAuthScheme.NTLM))
                        .setExpectContinueEnabled(true)
                        .build())
                .build()))
        .build();

    ParameterizedTypeReference<LinkedHashMap<String, Object>> result =
        new ParameterizedTypeReference<LinkedHashMap<String, Object>>() {};

    Map<String, Object> body = new HashMap<>();
    body.put("test-key", "value");
    webClient.post().uri("http://example.com:89/api/v1/employee").contentType(MediaType.APPLICATION_JSON).accept(MediaType.ALL).bodyValue(body).retrieve().bodyToMono(result).block();

Is this right approach?

halfer
  • 19,824
  • 17
  • 99
  • 186
Lolly
  • 34,250
  • 42
  • 115
  • 150

0 Answers0