How to use proxy and ignore specific request ssl errors - javascript

Good day, I am trying to connect to a third party rest API which is kinda old and has its certificate expired. I am using NodeJS and axios for sending request which at the moment looks something like this.
agent = new HttpsProxyAgent({ host, port, auth: `${uname}:${pass}` });
this.client = axios.create({
baseURL: this.baseUrl,
headers: this.headers,
httpsAgent: agent,
});
the agent above creates a proxy agent so my request would tunnel through that host which i am later mounting on axios, i am using this package https-proxy-agent. Now the proxy works fine and all, but it throws an error certificate has expired. I have tried to use rejectUnauthorized: false but that didn't work at all, however i found one more solution and that is to use NODE_TLS_REJECT_UNAUTHORIZED=0. But it is widely described as dangerous to use on the server, i also wonder if i will use this environment variable would it make client requests visible when intercepting?
What i need here is to just connect to the proxy and reject certificate errors only for this axios client, if there are solutions for other http clients feel free to share, thank you very very much.

Managed to solve the issue with a different package.
import { getProxyHttpAgent } from 'proxy-http-agent';
const proxyUrl = `http://${host}:${port}`;
agent = getProxyHttpAgent({
proxy: proxyUrl,
endServerProtocol: 'https:',
rejectUnauthorized: false,
});
setting agent with this package works great, except for some reason i have to use non authentication based proxy otherwise it would throw some weird ssl error which looks like this
tunneling socket could not be established, cause=write EPROTO 20920:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:c:\ws\deps\openssl\openssl\ssl\record\ssl3_record.c:332:.

Related

How to authenticate ngrok password automatically using Python and or Javascript?

I am using ngrok to expose my localhost on a raspberry pi, and ngrok is password protected. I am using Django on another computer outside my network to access a webpage(simple server) on this raspberry pi. I don't want to manually type in the username and password to ngrok.
How can I automatically fill in the ngrok user/password, which is a popup in chrome asking for user and password?
What I've tried:
I first tried using JS in my template, just using a fetch request:
https://user:password#myngrokdomain.ngrok.io but chrome threw an error in the console saying I can't pass in credentials in plain text like this, rightfully so...
I then tried to use python requests:
UN= "myuser"
PWD = "mypassword"
loginURL = "https://myngrokdomain.ngrok.io"
client = requests.session()
login_data = dict(username=UN, password=PWD,)
r = client.post(loginURL, data=login_data)
This returned a 401 access denied
r.headers + r.reason returns:
401 Unauthorized Unauthorized {'Content-Length': '16', 'Content-Type': 'text/plain', 'Www-Authenticate': 'Basic realm="ngrok"', 'Date': 'Tue, 16 Mar 2021 15:22:15 GMT'}
The authentication method used by ngrok is called HTTP Basic Auth. To use it with the requests library you pass login and password as a tuple in the auth argument:
r = client.post(loginURL, auth=(UN, PWD))
Docs: Basic Authentication — Requests
Try doing a get on the login page first. Perhaps it's setting some cookies that it expects to be present on the post :
UN= "myuser"
PWD = "mypassword"
loginURL = "https://myngrokdomain.ngrok.io"
client = requests.session()
login_data = dict(username=UN, password=PWD,)
client.get(loginURL )
r = client.post(loginURL, data=login_data)
You need to distinguish whether you're making the request from a browser or from a server application.
Browser
If you're doing it from a browser you're hitting a CORS issue and ngrok doesn't support that when providing --auth. From the docs:
you cannot use ngrok's -auth option. ngrok's http tunnels allow you to specify basic authentication credentials to protect your tunnels. However, ngrok enforces this policy on all requests, including the preflight OPTIONS requests that are required by the CORS spec. In this case, your application must implement its own basic authentication
In this case, your only option is to implement authentication in your application instead of using ngrok's --auth.
Server
If you're sending the request from a server application you won't get into any CORS issue but you need to provide the Basic Authentication credentials properly.
Say you have your application exposed via ngrok at http://myapp.ngrok.io protected via --auth user:pass.
In plain Node.js you would do something like this:
const http = require('http')
http.get('http://myapp.ngrok.io', { auth: 'user:pass' }, res => {
const chunks = []
res.on('data', chunk => {
chunks.push(chunk)
})
res.on('end', () => {
console.log(Buffer.concat(chunks).toString('utf-8'))
})
})
Note that to hit the https url you would use Node's https module instead of http, or a higher level library that handles that for you, like node-fetch.
In Python you can do something similar and this question will probably get you on the right path.

Access-Control-Allow-Origin is not * but Chrome insists it is (after upgrading apollo-server)

There were some features I wanted from apollo-server and spent some time refactoring my code to it (was previously using express-graphql). The only problem now is a "CORS" problem between my web app (using apollo-client) for authenticated requests. I recall having this problem as well back in version 1.x, and spent a lot of time wrestling with it, but my previous solution does not work in 2.x and would greatly appreciate some help for anyone who has managed to get this to work.
my webapp is hosted on localhost:8081
my server is hosted on localhost:4000
Following their code verbatim from here, I have the following:
Client code
const client = new ApolloClient({
link: createHttpLink({
uri: 'http://localhost:4000/graphql',
credentials: 'include'
})
})
Server code
// Initializing express app code
var app = ....
// Using cors
app.use(cors({
credentials: true,
origin: 'http://localhost:8081',
}));
// Apollo Server create and apply middleware
var apolloServer = new ApolloServer({ ... });
apolloServer.applyMiddleware({ app })
When the client queries the backend via. apollo-client, I get the following error in Chrome:
Yet in my server code, I am explicitly setting the origin. When I inspect the network request in console, I get a contradictory story as well as Access-Control-Allow-Origin explicitly is set to http://localhost:8081
I don't encounter this problem when using Insomnia to query my backend server and get the expected results. Does anyone have any experience setting up apollo on client and server on localhost and successfully authenticating?
I'm actually just dumb. I was looking at the wrong response, sideshowbarker was onto it, apollo-server-v2 automatically overrides CORS and sets the Access-Control-Allow-Origin header to * by default. Even if your express app specifies CORS and you apply that as a middleware to the apollo-server, this setting will be overridden for GraphQL routes. If anyone faces this problem, hopefully this'll save some time:
https://github.com/apollographql/apollo-server/issues/1142
You can now specify CORS explicitly for apollo-server in its applyMiddleware method:
https://www.apollographql.com/docs/apollo-server/api/apollo-server.html#Parameters-2

Slack oauth.access API returns bad_redirect_uri without requesting a redirect_uri

Trying to setup oAuth with slack for custom app and slack's API is returning {"ok":false,"error":"bad_redirect_uri"}. I'm not setting a redirect for oauth.access, even if I do set one I still get same error.
The app is configured to allow localhost and public domain.
This is the request I am doing
const res = await request({
method: 'post',
uri: 'https://slack.com/api/oauth.access',
auth: {
user: process.env.SLACK_CLIENT_ID,
pass: process.env.SLACK_CLIENT_SECRET,
},
form: {
code,
// redirect_uri: 'http://localhost:3100',
},
});
To kick off auth flow I am calling this URL from browser:
https://slack.com/oauth/authorize?client_id=XXX&scope=commands,im:read,im:write&redirect_uri=http://localhost:3100/integrations/slack.request&state=ID
You can not use localhost as redirect_uri.
If you want to use OAuth with your local PC, I would suggest installing a VPN tunnel like ngrok, that allows you to expose your local PC to the Internet in a relatively safe way. ngrok is also mentioned in one of the official Slack tutorials as example on how setup a local development environment with Slack.
Also make sure you have a webserver installed on your PC.

pouchdb remote db replication "unauthorised" Cookie credentials ignored in electron app

Issue
I have an electron app, I managed to login to couchdb with cookie auth.
I also manage to retrieve the correct session. I used the fetch api so far to handle the requests.
For cookie storage in electron I use electron-cookies and this is working, if I do another request with credentials: 'include' and 'withCredentials' : true options (after login in) it makes the request with the cookie (Cookie:AuthSession=...).
Whenever a user is created in my app a corresponding database is created too with the new user being the admin of that database. So far so good.
This setup works to 100% in postman.
However, if I try to sync to the remoteDB with PouchDB this does not work, I get an unauthorized error.
My guess is that the authentification cookie is somehow ignored by PouchDB.
I tried way:
remoteDB = new PouchDB('http://somecorrecturl/userDBName');
and also like this:
remoteDB = new PouchDB('http://somecorrecturl/userDBName', {
ajax: {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
'withCredentials' : true
},
credentials: 'include',
withCredentials: true,
}
});
without success.
( I also don’t see a request going out in the Network tab, this could be normal due to the nature of electron(?) tho’ )
Is there some special option I have to include? Using the fetch api for example I had to add credentials: 'include' before it would use the session cookie.
Is cookie auth even possible with pouchdb?
Or is there a way to sync a pouchdb with a couchdb "natively" without using the pouchdb api?
Doing the exact same thing with the same auth-cookie but using postman works. So my bet is that the cookie is ignored by pouchdb.
Info
Environment: Node.js / Electron
Platform: Chromium / Electron
Adapter: PouchDB
Server: CouchDB
Thank you for your help!

Connecting to an HTTPS service with SproutCore

I'm building a web app that requires me to connect to a service (https) to get some data. The web app is to be built using SproutCore. Now, I'm super new to SproutCore, and haven't been able to get to connect to the service. Some folks on the irc channel were super helpful and told me that to connect to an https service, I need to add a line in my BUILDFILE that says:
proxy '/path', :to => "https://myWebService.com", :secure => true
I did that. However, if I try to navigate to the url using:
SC.Request.getUrl('/path').notify(this, 'notifyMe').send();
I get a 404:
GET http://localhost:4020/path 404 (Not Found).
Any idea as to how I can connect to my HTTPS service. Additionally, I would like to state that once I connect, I would need to authenticate with it using basic auth (username and password).
Thanks all!
EDIT: Just wanted to mention that this request is Cross-Domain. I was under the impression that GET worked just fine cross domain.
Change:
proxy '/path', :to => "https://myWebService.com", :secure => true
to
proxy '/', :to => "myWebService.com", :secure => true
then
SC.Request.getUrl('/path').notify(this, 'notifyMe').send();
should work

Categories

Resources