How to fetch() with ssl client authentication? - javascript

Background: I am building a chrome extension that sends a simple http request and should be able to work with ssl client authentication.
Goal: Send a fetch request to a site with ssl client authentication without user having to open the site first.
What happens so far:
The request is only successful after i open the site manually.
Attempted using credentials: 'include' as suggested here - didn't solve the issue.
Im getting TypeError: failed to fetch
Fetch API docs # Mozilla don't seem to mention this (here and here)
fetch is sent as follows:
fetch(url)
.then(response => {
if(!response.ok){
throw Error("Http request failed");
}else{
return response
}
})
.then(response => response.text())
.then(validate => validate.replace(/\D/g,''))
.then(count => {
chrome.action.setBadgeText({text: count});
if(callback){
callback();
}
})
.catch(error => {
console.log(error)
if(callback){
callback();
}
});
I would be very grateful if you could guide me on what might be the issue.

Related

Fetching error on my chrome console I tried using different browses as well but still not solved

Fetching error on my chrome console I tried using different browsers as well but still not solved
fetch('https://api.cryptonator.com/api/ticker/btc-usd')
.then(res => {
console.log("Response Awaits to Parse");
})
.then(data => {
console.log("Data Parsed");
console.log(data.ticker.price);
})
.catch(e => {
console.log("Error NO!!!", e);
})
enter image description here
enter image description here
You are getting a 503 Error, which means the server is not ready to handle the request. Basically it means the problem is on the server side, not on you app. Check here for more info https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/503?retiredLocale=uk

React native fetch data

I have a problem with fetch data. My friend creates Rest Api.
There is my fun:
const AnyCors = `https://cors-anywhere.herokuapp.com/`;
const urlAllBus = `http://207.185.72.111:15430/stops?size=15`;
fetchBusStop = () => {
return new Promise((resolve, rejects) => {
fetch(AnyCors+urlAllBus)
.then((result) => {
if (!result.ok) throw result.json();
return result.json();
})
.then((result) => {
console.log(result);
resolve(result);
})
.catch((error) =>
error.then((body) => {
console.log('Bad', body);
rejects(body);
}),
);
});
};
I create an app with react-native. When I use only urlAllBus my virtual machine work fine. The problem is with a physical machine. When I try using my fun with urlAllbus in chrome I get a problem with CORS so I used AnyCors+urlAllBus and everything works fine. But in the virtual and physical machine there solutions not work. I don't know what I should do
You friend's API should accept CORS by adding a Access-Control-Allow-Origin: * header to its responses to allow any website to access it. They can also limit access to a specific site by setting the header to the base URL of such site, like Access-Control-Allow-Origin: http://example.com.
If the API is express-based, I hightly recommend the cors package for the job, as it makes it a single-line change.
Otherwise, tell them to give this MDN page a read for more information about CORS :)

Why am I getting generic "TypeError: Failed to fetch" errors?

When fetching from some APIs, I get TypeError: Failed to fetch errors.
For example, the URL used in the snippet below is an example provided by an API provider. It can be accessed without a key. It works fine in my browser but will throw an error in my code.
Fetching from another public API, https://api.punkapi.com/v2/beers/random, works perfectly.
What is the difference between these APIs that prevents me fetching from some and works for others others?
export default function App() {
useEffect(() => {
fetch(
'https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=439d4b804bc8187953eb36d2a8c26a02'
)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => {
console.error(error);
});
}, []);
return null;
}
you can't get data from samples
caused API is blocked due to CORS header ‘Access-Control-Allow-Origin’ missing
you need to generate api key(https://openweathermap.org/price) and connect to api
//ex:
api.openweathermap.org/data/2.5/weather?appid={your api key}&....

Cannot get data from data from end point due to the cors policy

I have the same problem as this guy. 'Can't get request a link with Axios due to No 'Access-Control-Allow-Origin' header is present on the requested resource' .
But it's weird that i can get data from this endpoint by Postman and even from another project.
axios.get('https://min-api.cryptocompare.com/data/all/coinlist')
.then(res => { // data
console.log(res.data) //console
})
.catch(function (error) { //errors
console.log(error);
});
const setAuthToken = token => {
if(token) {
axios.defaults.headers.common['Authorization'] = token;
} else {
delete axios.defaults.headers.common['Authorization']
}
};
Maybe there is some workaround. I am using node js as backend but only for register and login users, i don't think that this can have some impact. But i am making the token request using headers, maybe that's the problem?
The solution is simple. I only need to clear headers via delete axios.defaults.headers.common["Authorization"] before my request

gmail.users.watch fails to send test message to PubSub with a DwD service account

I'm trying to setup gmail.users.watch but am getting a 403 error:
Error sending test message to Cloud PubSub projects/project-id/topics/topic-id : User not authorized to perform this action.
Authentication is working using the GOOGLE_APPLICATION_CREDENTIALS approach and the downloaded credentials json file.
The following code works correctly which supports my hypothesis that the authentication is generally working:
const pubsub = PubSub();
const topic = pubsub.topic('topic-id');
const subscription = pubsub.subscription('subscription-id');
topic.exists()
.then(data => {
console.log(data);
return subscription.exists();
})
.then(data => {
console.log(data);
return subscription.pull()
})
.then(data => {
data[1].receivedMessages.forEach(d => console.log(d));
return topic.publish('Hello, world!');
})
.then(data => {
console.log(data)
})
.catch(err => console.log(err));
No errors from that code. However the following code throws the 403 error described above:
const authParams = {
subject: userId,
scopes: [
'https://mail.google.com/',
'https://www.googleapis.com/auth/pubsub'
]
};
gauth.getAuth(authParams)
.then(authClient => {
const params = {
auth: authClient,
userId: 'me',
resource: {
topicName: <topic-id>
}
};
return new Promise((resolve, reject) => {
gmail.users.watch(params, (err, response) => {
if (err) {
console.log(err);
reject(err);
return;
}
resolve(response);
});
});
})
.then(response => {
console.log(response);
});
gauth.getAuth is a simple wrapper around getApplicationDefaultGoogle Auth Library for Node.js.
The G Suite domain security Client Access is configured with the Client ID of the service account against the scopes needed:
https://www.googleapis.com/auth/pubsub, https://mail.google.com/
As the native cloud pub/sub stuff works I think the service account has all of the correct permissions configured on the console so I'm a bit at a loss as to why the gmail call is failing.
UPDATE:
Service Account has the following permissions on Google Cloud Console:
Project: (Does it need more than this for the gmail stuff?)
Service Account Actor
PubSub Admin
Topic:
Owner
Subscription:
Owner
When making the gmail call the service account is delegating to a 'subject'. I've added permissions for that subject userId to the Google Cloud Console:
Project:
Owner
Topic:
Owner
Subscription:
Owner
You need to add permissions so messages can be publish to your subscription.
Go to Google Cloud console, select the subscription and then Permissions.
In the Add members section, type allAuthenticatedUsers, select the Pub/Sub publisher role and click Add
Does it help?
Update (2017/05/09):
I'm editing my answer in order to be more accurate about what's needed.
According to the Gmail API documentation (see the Grant publish rights on your topic section):
the permission needs to be set at the topic level
the member is: serviceAccount:gmail-api-push#system.gserviceaccount.com
the role is: Pub/Sub Publisher

Categories

Resources