Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[msal-node] Issues when server is behind proxy #2600

Closed
1 of 8 tasks
ben-sf opened this issue Nov 16, 2020 · 38 comments
Closed
1 of 8 tasks

[msal-node] Issues when server is behind proxy #2600

ben-sf opened this issue Nov 16, 2020 · 38 comments
Assignees
Labels
enhancement Enhancement to an existing feature or behavior. feature Feature requests. msal-node Related to msal-node package tracked-internally Bugs that are tracked by Msft internally

Comments

@ben-sf
Copy link

ben-sf commented Nov 16, 2020

Please follow the issue template below. Failure to do so will result in a delay in answering your question.

Library

  • msal@1.x.x or @azure/msal@1.x.x
  • @azure/msal-browser@2.x.x
  • @azure/msal-node@1.0.0-alpha.5
  • @azure/msal-react@1.x.x
  • @azure/msal-angular@0.x.x
  • @azure/msal-angular@1.x.x
  • @azure/msal-angular@2.x.x
  • @azure/msal-angularjs@1.x.x

##Framework:
NodeJS

Description:

When proxy is configured for NodeJS we are getting the following error. We should have the ability to pass the proxy configuration to the NetworkClient.

Error Message:

ClientAuthError: endpoints_resolution_error: Error: could not resolve endpoints. Please check network and try again. Detail: ClientConfigurationError: untrusted_authority: The provided authority is not a trusted authority. Please include this authority in the knownAuthorities config parameter.

Reproduction steps

  1. Set nodeJS proxy settings (process.env['HTTPS_PROXY'] and process.env['HTTP_PROXY'])
  2. Call getAuthCodeUrl function

Expected behavior

We should be able to call msal-node functions when behind proxy

@ben-sf ben-sf added the bug A problem that needs to be fixed for the feature to function as intended. label Nov 16, 2020
@sameerag
Copy link
Member

@ben-sf Can you please provide your configuration info? The app needs to include the authority in the knownAuthorities parameters if you are using a B2C or a third party authentication endpoint. Usage is documented here.

@ben-sf
Copy link
Author

ben-sf commented Nov 16, 2020

@sameerag Thank you for the quick response.
See below my configuration info:
{
auth: {
clientId: '<MY_CLIENT_ID>',
authority: 'https://login.microsoftonline.com/<MY_TENANT_ID>',
clientSecret: '<MY_CLIENT_SECRET>'
},
system: {
loggerOptions: {
loggerCallback(loglevel, message) {
console.log(message);
},
piiLoggingEnabled: false,
logLevel: msal.LogLevel.Verbose
}
}
}

What I need to change to make it work? (for Example let say my proxy ip address is http://192.168.1.1)

@ben-sf
Copy link
Author

ben-sf commented Nov 23, 2020

@sameerag did you see my attached configuration?

@sameerag
Copy link
Member

I am trying to reproduce on my end. Will update in a couple of days. How urgent is this?

@ben-sf
Copy link
Author

ben-sf commented Nov 24, 2020

@sameerag It can wait couple of days. Thanks!

@github-actions
Copy link
Contributor

github-actions bot commented Dec 9, 2020

This issue has not seen activity in 14 days. It will be closed in 7 days if it remains stale.

@github-actions github-actions bot added the no-issue-activity Issue author has not responded in 5 days label Dec 9, 2020
@tnorling tnorling removed the no-issue-activity Issue author has not responded in 5 days label Dec 9, 2020
@sameerag
Copy link
Member

@ben-sf Apologies for the delay in our response. msal-node provides an interface to configure your own http clients. You can choose to pass your own implementation of INetworkModule referenced here.

This will be the best way to setup your proxy and have the library work. Please let us know if you have any further questions.

@hectormmg
Copy link
Member

We're may consider adding https-proxy-agent or something similar to MSAL Node in the future to support proxy requests, but there are no plans to do it yet. We'll update this issue if and when we do.

@wodeleeway
Copy link

Any progress on this? I am using the msal-node module and followed the auth code flow example. https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/samples/msal-node-samples/standalone-samples/auth-code/index.js

Without the proxy, it got untrusted authority error after a few seconds, seems like a final error returned with the timeout.
With the proxy, it got below:

{"errorCode":"endpoints_resolution_error","errorMessage":"Error: could not resolve endpoints. Please check network and try again. Detail: ClientAuthError: openid_config_error: Could not retrieve endpoints. Check your authority and verify the .well-known/openid-configuration endpoint returns the required endpoints. Attempted to retrieve endpoints from: https://login.microsoftonline.com//v2.0/.well-known/openid-configuration","subError":"","name":"ClientAuthError"}

@jasonnutter jasonnutter added the msal-node Related to msal-node package label Mar 15, 2021
@sameerag
Copy link
Member

@ben-sf @wodeleeway We have been considering something like this as @hectormmg mentioned above. We haven't yet started the work, this is slated to be picked up soon and we will update here once we have an active PR. Apologies for the wait, please note that we are tracking this.

@sameerag sameerag removed the bug A problem that needs to be fixed for the feature to function as intended. label Mar 24, 2021
@enima2684
Copy link

@sameerag Can you please provide an example of the INetworkModule implementation with a proxy ?
Many thanks !

@piotrlech
Copy link

Have the same, but the weird thing is that msal-node works fine (I think it gets the proxy from the browser) on 2 servers, but on the other one it doesn't, and I don't know why

@sameerag
Copy link
Member

Can you share the error you see here @piotrlech ?

@piotrlech
Copy link

signin error: ClientAuthError: endpoints_resolution_error: Error: could not resolve endpoints. Please check network and try again. Detail: ClientConfigurationError: untrusted_authority: The provided authority is not a trusted authority. Please include this authority in the knownAuthorities config parameter.
GET /auth/signin 302 31628.943 ms

So many ms means a timeout to me. When looking at the tcpdump I can see that the TCP syn request goes to the IP address of 20...sth, which is MS Azure. In the other good servers, the request goes correctly to the proxy instead. The browser setup is the same here and there.

@sameerag
Copy link
Member

This is interesting. Is it possible to share the fiddler's trace for success and failure cases with us @piotrlech? You can email me, my email is available in my profile. I am curious what configuration is causing this error.

Also is it the same app all these scenarios? If they are different apps, can you please share the config details in each case?

@sameerag
Copy link
Member

Also, the proxy settings you made, if possible.

@Bjego
Copy link

Bjego commented May 3, 2021

Hey guys, I've implemented a proxy client:

The proxy is set automatically via env variable then:
export HTTP_PROXY=http://your.proxy:8888
more: https://www.npmjs.com/package/node-fetch-with-proxy

proxyclient.js

const fetch = require('node-fetch-with-proxy');

async function sendGetRequestAsync(url, options) {
  const response = await fetch(url, options);
  const json = await response.json();
  const headers = response.headers.raw();
  return {
    headers: Object.create(Object.prototype, headers),
    body: json,
    status: response.status
  }
}

async function sendPostRequestAsync(url, options) {
  const sendingOptions = options || {};
  sendingOptions.method = 'post';
  const response = await fetch(url, sendingOptions);
  const json = await response.json()
  const headers = response.headers.raw();
  return {
    headers: Object.create(Object.prototype, headers),
    body: json,
    status: response.status
  }

}

module.exports = {
  sendGetRequestAsync,
  sendPostRequestAsync
}

and in my main:

const msal = require('@azure/msal-node');
const client = require('./proxyClient.js');



async function main() {
  const msalConfig = {
    auth: {
      clientId: 'STRING',
      authority: 'STRING',
      clientSecret:'STRING',
    },
    system: {
      networkClient: client
    }
  };

  const tokenRequest = {
    scopes: ['https://graph.microsoft.com/.default'],
  };

  const cca = new msal.ConfidentialClientApplication(msalConfig);
  const authResponse = await cca.acquireTokenByClientCredential(tokenRequest);
  console.log(authResponse.accessToken) // display access token

}


main()
  .catch(console.log))
  .then(_ => process.exit());

@Nexyll
Copy link

Nexyll commented Jul 15, 2021

I'm facing the same issue, even with the node-fetch-with-proxy client as describe in @Bjego solution's

@sameerag
Copy link
Member

We think this is axios not supporting proxy: axios/axios#2072 (comment); Can you please try the alternative they suggested and let us know?

@Nexyll
Copy link

Nexyll commented Jul 16, 2021

Hi,

After some tests, the solution given by @Bjego works correctly for authentication. To send requests with Axios I had to use https-proxy-agent

const HttpsProxyAgent = require('https-proxy-agent')
const agent = new HttpsProxyAgent('http://127.0.0.1:3128');
return {
    headers: {
        Accept: "application/json;odata=verbose",
        Authorization: `Bearer ${this.cachedAccessToken}`
    },
    httpsAgent: agent
};

Now it works properly, thanks.

@Tcharl
Copy link

Tcharl commented Jul 19, 2021

Hi Everyone,

We're struggling with that too: we've tried using global-agent library, put simply importing it and calling bootstrap does not look sufficient.
Can you please describe the overall code?

Thank you very much in advance

@Bjego
Copy link

Bjego commented Jul 20, 2021

Interesting that so many people still struggeling. Have you tried to trust your inhouse cert in node? You can do this by the environmentvariable: https://nodejs.org/api/cli.html#cli_node_extra_ca_certs_file
in k8s

                - name: NODE_EXTRA_CA_CERTS
                  value: /usr/local/share/ca-certificates/MYCORPORATECERT.crt

or plain linux

export NODE_EXTRA_CA_CERTS=/usr/local/share/ca-certificates/MYCORPORATECERT.crt

more: https://linuxconfig.org/how-to-set-and-list-environment-variables-on-linux#:~:text=%20How%20to%20set%20and%20list%20environment%20variables,order%20to%20configure%20a%20new%20environment...%20More%20

@Tcharl
Copy link

Tcharl commented Jul 20, 2021

Sure, I even usually add my ca into the trusted system ca store.
I do not really like adding the CA by runtime, but it's a matter of preference ;-)

@prandell
Copy link

Hi guys, @Nexyll how were you able to get @Bjego's solution to work? I am still getting the same error when trying to authenticate with the updated network client.

@abhi12299
Copy link

abhi12299 commented Aug 12, 2021

Facing the same issue. I used the networkClient proxy as provided in the above comments. Although in my case, it works sometimes for a few hours and breaks after that :(

@justinmchase
Copy link

We are also encountering this, but only for users running in WSL. The exact same code on developers running macs there are no issues but if run through WSL it has an issue.

@piotrlech
Copy link

Note that sometimes helps if you set your HTTP_PROXY and HTTPS_PROXY in the .env file

@martin-dimitrov13
Copy link

martin-dimitrov13 commented Dec 14, 2021

I made it work with axios and https-proxy-agent but that completely circumvents msal-node. Ideally we would be able to provide it with our own https agent. Just like in msal-net :
https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-net-provide-httpclient

@san-goyal
Copy link

We are also facing same issue. Could someone please share the code snippet to resolve the issue?

Dependency
@azure/msal-node": "^1.3.0"

Config

const msal = require('@azure/msal-node');
const config = {
            auth: {
                clientId: <<clientID>>,
                authority: https://login.microsoftonline.com/${tenantID}/,
                clientSecret: <<clientSecret>>
            },
            system: {
                loggerOptions: {
                    loggerCallback(loglevel, message, containsPii) {
                        console.log(message);
                    },
                    piiLoggingEnabled: false,
                    logLevel: msal.LogLevel.Error,
                }
            }
        };

        const cca = new msal.ConfidentialClientApplication(config);
        const clientCredentialRequest = {
            scopes: ["https://graph.microsoft.com/.default"],
        };
        cca.acquireTokenByClientCredential(clientCredentialRequest).then((response) => {
            resolve(response.accessToken);
        }).catch((error) => {
            console.log(JSON.stringify(error));
            reject(error);
        })

Error

Failure
Exception: ClientAuthError: endpoints_resolution_error: Error: could not resolve endpoints. Please check network and try again. Detail: ClientConfigurationError: untrusted_authority: The provided authority is not a trusted authority. Please include this authority in the knownAuthorities config parameter.
Stack: ClientAuthError: endpoints_resolution_error: Error: could not resolve endpoints. Please check network and try again. Detail: ClientConfigurationError: untrusted_authority: The provided authority is not a trusted authority. Please include this authority in the knownAuthorities config parameter.
    at ClientAuthError.AuthError [as constructor] (C:\home\site\wwwroot\node_modules\@azure\msal-common\dist\index.cjs.js:477:24)

@Robbie-Microsoft
Copy link
Collaborator

@san-goyal per your error message, you may want to add the following to your auth block:
knownAuthorities: ["https://login.microsoftonline.com/${tenantID}/,"]

@san-goyal
Copy link

@Robbie-Microsoft thanks for your response.

Now code started throwing different error. 240 out of 2400 requests got failed. Behavior is intermittent.

Exception while executing function: Functions.QueueTriggerFunction Result: Failure
Exception: ClientAuthError: endpoints_resolution_error: Error: could not resolve endpoints. Please check network and try again. Detail: ClientAuthError: openid_config_error: Could not retrieve endpoints. Check your authority and verify the .well-known/openid-configuration endpoint returns the required endpoints. Attempted to retrieve endpoints from: https://login.microsoftonline.com/<<tenant_guid>>/v2.0/.well-known/openid-configuration
Stack: ClientAuthError: endpoints_resolution_error: Error: could not resolve endpoints. Please check network and try again. Detail: ClientAuthError: openid_config_error: Could not retrieve endpoints. Check your authority and verify the .well-known/openid-configuration endpoint returns the required endpoints. Attempted to retrieve endpoints from: https://login.microsoftonline.com/<<tenant_guid>>/v2.0/.well-known/openid-configuration
    at ClientAuthError.AuthError [as constructor] (D:\home\site\wwwroot\node_modules\@azure\msal-common\dist\index.cjs.js:481:24)
    at new ClientAuthError (D:\home\site\wwwroot\node_modules\@azure\msal-common\dist\index.cjs.js:771:28)
    at Function.ClientAuthError.createEndpointDiscoveryIncompleteError (D:\home\site\wwwroot\node_modules\@azure\msal-common\dist\index.cjs.js:808:16)
    at Function.<anonymous> (D:\home\site\wwwroot\node_modules\@azure\msal-common\dist\index.cjs.js:7131:47)
    at step (D:\home\site\wwwroot\node_modules\@azure\msal-common\dist\index.cjs.js:79:23)
    at Object.throw (D:\home\site\wwwroot\node_modules\@azure\msal-common\dist\index.cjs.js:60:53)
    at rejected (D:\home\site\wwwroot\node_modules\@azure\msal-common\dist\index.cjs.js:51:65)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:95:5) 

@sameerag
Copy link
Member

@san-goyal Did you try the latest msal-node release?

We added proxy support in the latest msal-node release @azure/msal-node version 1.6.0 with the change log details here

Please let us know if this solves your issue.

@sameerag
Copy link
Member

sameerag commented Apr 2, 2022

We support proxy with axios but noticed that axioss support is at best patchy with proxies. The latest is supporting proxy with hpagent and development is currently in progress. cc @Robbie-Microsoft @EmLauber

@sameerag
Copy link
Member

Closing this. We have a custom proxy implementation now with node http/https and should solve this issue.

@GurpreetVirdi
Copy link

@sameerag : You said "we have a custom proxy implementation now with node http/https and should solve this issue." ? Can you provide an example please ?

I am getting this error while running my nodejs Lambda function backed by MSAL-NODE to fetch the token ; Using "@azure/msal-node": "^1.6.0"

"Detail: ClientAuthError: openid_config_error: Could not retrieve endpoints. Check your authority and verify the .well-known/openid-configuration endpoint returns the required endpoints."

***********CODE SNIPPET **********
const msalConfig = {
auth: {
clientId: msClientId!,
clientSecret: msClientSecret,
authority: https://login.microsoftonline.com/${msTenantId}/,
knownAuthorities: [https://login.microsoftonline.com/${msTenantId}/],

            }
        }
        const cca = new msal.ConfidentialClientApplication(msalConfig);
        const authResponse = await cca.acquireTokenByClientCredential({
            scopes: [scope!]
        });

Also you mentioned in the change log for 1.6.0 :: "Support proxy in msal-node(#4447)"

Can you please tell how to leverage that custom proxy ?

@Robbie-Microsoft
Copy link
Collaborator

@GurpreetVirdi You can find documentation on proxy support in the configuration README for MSAL-Node. It's located here: https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-node/docs/configuration.md

@GurpreetVirdi
Copy link

@Robbie-Microsoft : Not able to find. The link that you posted has no mention of any "PROXY SUPPORT/ CONFIG" and also I am using ConfidentialClientApplication in my Lambda <Authenticating API's deployed to different accounts> and not PublicClientApplication ; please show the way!

Looks like my app is trying to call ' .well-known/openid-configuratio' GET endpoint but its blocked. I am running this in AWS managed environment.

@Robbie-Microsoft
Copy link
Collaborator

Search for "proxy" on that link I posted, you will find the documentation. It will tell you that you need to provide a "proxyUrl" to the system settings in the config. It functions the same no matter if your application is public or confidential.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement Enhancement to an existing feature or behavior. feature Feature requests. msal-node Related to msal-node package tracked-internally Bugs that are tracked by Msft internally
Projects
None yet
Development

No branches or pull requests