Add proxy server configuration to MSAL4J java library method to authenticate to Microsoft.

Abhijit Nagle 0 Reputation points
2023-12-08T19:04:25.8166667+00:00

I am using MSAL4J java library to authenticate to Microsoft using certificate, my code is working fine but I want my code to use proxy server for authentication.

I found https://learn.microsoft.com/en-us/entra/msal/java/advanced/configure-http-client but not able modify the class in a right way to use proxy configuration.

Below is my code, kindly let me know what should I do.

 

private static IAuthenticationResult getAccessTokenByClientCredentialGrant(String authority, String clientId, String keystorePath, String certPath, String scope, String keystorepwd, String keystorealias, String proxy, String pUsr, String pPwd) 
        throws FileNotFoundException, IOException, Exception 
    {
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        //InputStream keyStoreData = new FileInputStream(keystorePath);
        InputStream keyStoreData = null;
        try {
            keyStoreData = new FileInputStream(keystorePath);
            keyStore.load(keyStoreData, keystorepwd.toCharArray());
        } finally {
            if (keyStoreData != null) {
                try {
                    keyStoreData.close();
                } catch (IOException e) {
                    throw e;
                }
            }
        }
        
        PrivateKey key = (PrivateKey) keyStore.getKey(keystorealias, keystorepwd.toCharArray());
        InputStream certStream = new ByteArrayInputStream(Files.readAllBytes(Paths.get(certPath)));
        X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(certStream);
        
        ConfidentialClientApplication  app = ConfidentialClientApplication.builder(
                        clientId,
                        ClientCredentialFactory.createFromCertificate(key, cert))
                        .authority(authority)
                        .build();
              
        ClientCredentialParameters clientCredentialParam = ClientCredentialParameters.builder(
                Collections.singleton(scope))
                .build();
    
        CompletableFuture<IAuthenticationResult> future = app.acquireToken(clientCredentialParam);
        
        return future.get();
    }
Microsoft Security | Microsoft Entra | Microsoft Entra ID
Microsoft Security | Microsoft Graph
Microsoft Security | Microsoft Identity Manager
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.