question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

NextAuth not working behind corporate proxy

See original GitHub issue

Description 🐜

NextAuth is not working behind corporate proxy.

I studied the current NextAuth implementation and found that this error happens because NextAuth makes use of the “node-auth” library (npm package “oauth”) in it’s “oAuthClient” (src/server/lib/oauth/client.js), which requires manually setting up an agent to be used by the “https” library.

I created a PR with the solution of the problem: https://github.com/nextauthjs/next-auth/pull/2493

Related discussion: https://github.com/nextauthjs/next-auth/discussions/676 Related StackOverflow: https://stackoverflow.com/questions/32130471/node-js-https-not-working-behind-corporate-proxy

If the PR is not going to be accepted, i believe it is important do register the issue here for other people facing the same problems that i’m facing right now (which are quite time consuming to debug).

Is this a bug in your own project?

No

How to reproduce ☕️

Just run any application with NextAuth behind a corporate proxy and try to log in with a Provider (like Google or GitHub).

Screenshots / Logs 📽

[next-auth][error][oauth_get_access_token_error] 
https://next-auth.js.org/errors#oauth_get_access_token_error Error: connect ETIMEDOUT 216.58.202.141:443
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16) {
  errno: -4039,
  code: 'ETIMEDOUT',
  syscall: 'connect',
  address: '216.58.202.141',
  port: 443
} undefined undefined
[next-auth][error][oauth_get_access_token_error]
https://next-auth.js.org/errors#oauth_get_access_token_error Error: connect ETIMEDOUT 216.58.202.141:443
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16) {
  errno: -4039,
  code: 'ETIMEDOUT',
  syscall: 'connect',
  address: '216.58.202.141',
  port: 443
} google 4/0AX4XfWiDMdHUjXWR1xqLs8bGa1g5CEJOdBiypyNPA3b4vzJHeqxOGFownSkn5ABA885Asw
[next-auth][error][oauth_callback_error]
https://next-auth.js.org/errors#oauth_callback_error Error: connect ETIMEDOUT 216.58.202.141:443
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16) {
  errno: -4039,
  code: 'ETIMEDOUT',
  syscall: 'connect',
  address: '216.58.202.141',
  port: 443
}

Environment 🖥

System: OS: Windows 10 10.0.19042 CPU: (12) x64 Intel® Core™ i7-8700 CPU @ 3.20GHz
Memory: 6.80 GB / 15.78 GB Binaries: Node: 14.16.1 - C:\Program Files\nodejs\node.EXE
Yarn: 1.22.5 - C:\Program Files (x86)\Yarn\bin\yarn.CMD npm: 6.14.12 - C:\Program Files\nodejs\npm.CMD Browsers: Edge: 44.19041.423.0 Internet Explorer: 11.0.19041.1 npmPackages: react: ^17.0.2 => 17.0.2

Contributing 🙌🏽

Yes, I am willing to help solve this bug in a PR

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:13 (6 by maintainers)

github_iconTop GitHub Comments

2reactions
raphaelpccommented, Feb 10, 2022

HEAD requests should not be a problem, see my comment: #3900 (review)

Regarding fixing with a patch, openid-clinet allows you to set your agent for requests: https://github.com/panva/node-openid-client/blob/main/docs/README.md#customizing-individual-http-requests if that is any helpful. We create the client here:

https://github.com/nextauthjs/next-auth/blob/68e412b063e824685529bddc1288ec88d41afe4b/packages/next-auth/src/core/lib/oauth/client.ts#L34

We let all openid-client settings pass through https://next-auth.js.org/configuration/providers/oauth#client-option but the agent setting is somewhat obscure (I think on purpose) and you can only modify it after the client has been created. So not sure if it would be possible without a change from us or patching.

Thanks for the tip.

I have now been able to patch NextAuth v4 to be able to use it behind corporate proxy.

This is what i did:

  1. First, i tried to resolve the problem directly through NextAuth configuration, exploring this option that is already provided:

https://github.com/nextauthjs/next-auth/blob/68e412b063e824685529bddc1288ec88d41afe4b/packages/next-auth/src/core/lib/oauth/client.ts#L16

To do so, i first updated my Provider at […nextauth].ts:

    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
      httpOptions: {
        agent: new HttpsProxyAgent(process.env.http_proxy),
      },
    }),

Doing like that it unfortunately didn’t work. I got this error:

message: 'The "options.agent" property must be one of Agent-like Object, undefined, or false. Received an instance of Object'

Probably because the way the “agent” is being received by the openidClient function makes it stop being a Agent-like Object.

  1. To finally resolve the issue locally, i’m using patch-package.

I’m applying this patch:

diff --git a/node_modules/next-auth/core/lib/oauth/client.js b/node_modules/next-auth/core/lib/oauth/client.js
index 77161bd..1082fba 100644
--- a/node_modules/next-auth/core/lib/oauth/client.js
+++ b/node_modules/next-auth/core/lib/oauth/client.js
@@ -7,11 +7,19 @@ exports.openidClient = openidClient;
 
 var _openidClient = require("openid-client");
 
+var HttpsProxyAgent = require("https-proxy-agent");
+
 async function openidClient(options) {
   const provider = options.provider;
-  if (provider.httpOptions) _openidClient.custom.setHttpOptionsDefaults(provider.httpOptions);
-  let issuer;
+  let httpOptions = {};
+  if (provider.httpOptions) httpOptions = { ...provider.httpOptions };
+  if (process.env.http_proxy) {
+    let agent = new HttpsProxyAgent(process.env.http_proxy);
+    httpOptions.agent = agent;
+  }
+  _openidClient.custom.setHttpOptionsDefaults(httpOptions);
 
+  let issuer;
   if (provider.wellKnown) {
     issuer = await _openidClient.Issuer.discover(provider.wellKnown);
   } else {

It would be great if this issue could be resolved in future versions! Maybe with an option like “useProxyAgent” that, if true, the openidClient function will check that a “process.env.http_proxy” exists and, if so, sets an HttpsProxyAgent like in my patch?

Anyway, in case anyone else has the same problem as i, i hope the patch can help! 😃

Thanks!

2reactions
ndom91commented, Sep 5, 2021

@raphaelpc we released a beta for the new NextAuth v4 version today which uses the newer openid-client instead of node-oauth. Unfortunately there is still no built-in support for proxying.

They use sindresorhus/got for http requests, and you can set a custom agent so it shouldn’t be too difficult to write up a workaround like the one you detailed here in your patch-package diff.

Notes:

Thinking out loud here based off the info in the above links… but maybe here (https://github.com/nextauthjs/next-auth/blob/beta/src/server/lib/oauth/client.js), adding something along these lines?

const { custom } = require('openid-client');
const { HttpsProxyAgent } = require('hpagent');

custom.setHttpOptionsDefaults({
  agent: {
    https: new HttpsProxyAgent({
	keepAlive: true,
	keepAliveMsecs: 1000,
	maxSockets: 256,
	maxFreeSockets: 256,
	scheduling: 'lifo',
	proxy: 'https://localhost:8080'
    })
  }
});
Read more comments on GitHub >

github_iconTop Results From Across the Web

corporate-proxy | NextAuth.js
Using NextAuth.js behind a corporate proxy is not supported out of the box. This is due to the fact that the underlying library...
Read more >
next-auth-proxy - npm
Start using next-auth-proxy in your project by running `npm i next-auth-proxy`. There are no other projects in the npm registry using ...
Read more >
Manual Chapter: Forward Proxy Chaining with APM - AskF5
For the BIG-IP ® system, proxy server, and resource servers behind the ... You configure an access policy to authenticate users on behalf...
Read more >
How to use a proxy in Next.js - LogRocket Blog
Going to a website without using a proxy is not considered secure in ... cuts through the noise to proactively resolve issues in...
Read more >
Implementing an HTTP Proxy for Rest API in Next.js
Unfortunately, it's not the safest place to store tokens. Local storage and normal cookies ... You must create a proxy server instance to...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found