I'm trying to retrieve a list of subscribed FCM topics for an app instance.
The documentation states that I should make a GET request at https://iid.googleapis.com/iid/info/<IID_TOKEN>?details=true, passing in Authorization:key=<WEB_API_KEY> as a header.
Here's how the request looks inside my client:
const getTopics = (token) => {
fetch('https://iid.googleapis.com/iid/info/${token}?details=true', {
headers: {
'Content-Type': 'application/json',
'Authorization': 'key=AIzaSy...dQ80g'
}
})
.then(res => console.log(res))
.catch(err => console.log(err))
}
const messaging = firebase.messaging()
messaging
.requestPermission()
.then(() => messaging.getToken())
.then(getTopics)
.catch(err => console.log(err))
And this is the response I'm getting:
Any ideas what I'm doing wrong here? Clearly one of my tokens is invalid, but according the documentation this should be correct.
In case anyone finds this question and needs an answer, I found the issue: the documentation is wrong, the Authorization header requires the cloud messaging project SERVER KEY. This is NOT the same as the general API key.
Here's where you can find the correct key as of Oct 2019:
Google, please keep your documentation up to date, I wasted hours trying to figure this out!
Related
The problem Overview
When getting products using a GET method everything works
when trying to update a product using PUT method I get 401 unauthorized
I use same credentials for both methods
The bearer token is global scope, I should be authorized to do anything to a given product
The code
GET
// javascript
const axiosOptions = {
headers: {
"Authorization": `Bearer ${token}`
}
}
const onAllClick = async () => {
const result = await axios.get(`https://api.printify.com/v1/shops/${shopId}/products.json?limit=30`, axiosOptions );
const products = result.data.data;
console.log(products);
}
PUT
javascript
const axiosTagUpdateOptions = {
headers: {
"Authorization": `Bearer ${token}`
},
data: {
title:"New product title"
}
}
const onEditTagsClick = async (productID, tags) => {
await axios.put(`https://api.printify.com/v1/shops/${shopId}/products/60e0a5c198be4c1296798c27.json`, axiosTagUpdateOptions)
.catch(err => console.log(err));
}
Problem
The get function works perfectly fine. But whenever I try to modify a product using the put method, like the documentation says, I get a 401 unauthorized error. But I'm using the same token for both the get and the put method. The token is set to global scope (for testing purposes) so I should be able to edit and delete products at will.
I read through the API documentation and it looks like I got everything right. I have the bearer token as the header and in the body I included the value I want to modify. Obviously the request is going through, I just don't know why it keeps saying I'm unauthorized to edit the product. I would have liked to edit the product from the printify UI, but the UI won't let me add tags (which is really annoying)... So I'm forced to update via a put method.
I couldn't find any reason for why I am getting this error, can anyone help me?
For put request you must pass data as a parameter and not in axiosOptions.
const onEditTagsClick = async (productID, tags) => {
await axios.put(`https://api.printify.com/v1/shops/${shopId}/products/60e0a5c198be4c1296798c27.json`, data, axiosTagUpdateOptions)
.catch(err => console.log(err));
}
I am looking to adjust the Fetch request option when making a request with #esri/arcgis-rest-request, but unfortunately I cannot find any documentation related to this.
import fetch from "node-fetch";
import FormData from "isomorphic-form-data";
import arcgisRestRequest from "#esri/arcgis-rest-request";
arcgisRestRequest.setDefaultRequestOptions({ fetch, FormData });
arcgisRestRequest.request("https://www.arcgis.com/sharing/rest/info")
.then(response => console.log(response));
When using the request method I am getting errors regarding the certificate of the NodeJS server:
FetchError: request to https://xxx/server/rest/self?token=xxx=json failed, reason: unable to get local issuer certificate
I would like to pass something like:
const fetchOptions = {
...
agent:new https.Agent({rejectUnauthorized: false}),
...
};
to avoid the certificate error.
How can I accomplish this?
Looking at their code it looks like you should be able to just do
arcgisRestRequest.request(
"https://www.arcgis.com/sharing/rest/info",
{
agent:new https.Agent({rejectUnauthorized: false})
}
)
.then(response => console.log(response));
I'm hoping to get the name, label, and due date of the first few cards in one of the Trello lists on my board and sending it over Discord using my bot. How would I go about getting this info?
You will have to work with there API, and with a fetch library to make requests. They gave some example of how to use their API like this :
// This code sample uses the 'node-fetch' library:
// https://www.npmjs.com/package/node-fetch
const fetch = require('node-fetch');
fetch('https://api.trello.com/1/cards?key=0471642aefef5fa1fa76530ce1ba4c85&token=9eb76d9a9d02b8dd40c2f3e5df18556c831d4d1fadbe2c45f8310e6c93b5c548&idList=5abbe4b7ddc1b351ef961414', {
method: 'POST'
})
.then(response => {
console.log(
`Response: ${response.status} ${response.statusText}`
);
return response.text();
})
.then(text => console.log(text))
.catch(err => console.error(err));
You have lot of option to deal with, and it's like php options (link/page?option=WhatsYouWAnt&option2=...).
All options are listed on the API page. It's using promises to return answer so be sure to know what's you're doing.
API : Trello API
I have read a lot of articles about refreshing token , but I didn't get nothing , they seems too complicated. Could you please explain me on my sample. I'm making sign-in , on response i'm getting object with access_token, refresh_token and timestamp. After I'm saving both tokens in localStorage. Later when access_token expires I receive 403 error(Forbidden). There is no message that token expired. Could you please help me with that
signIn(event) {
event.preventDefault()
const formdata = new FormData()
formdata.append("username", this.state.userLogin.email)
formdata.append("password", this.state.userLogin.password)
axios
.post("http://dev.****************.com/auth/get-token", formdata)
.then(res => {
if (res.data) {
localStorage.setItem("token", res.data.access_token)
localStorage.setItem("updToken", res.data.update_token)
this.setState({
isLoginError: false,
})
this.props.history.push("/settings")
}
})
.catch(error => {
if (error.response.status === 403) {
this.setState({
isLoginError: true,
})
}
})
}
There are two generally accepted ways to go about this:
periodically request a refreshed token based on the provided ttl in your original token -- for example, if your original token has a ttl of, say, 3600 seconds, then have a window.setInterval which refreshes every 3530 seconds. This works, but doesn't handle if auth has changed for some other reason.
Better: install an http interceptor to handle a 401 and retry the request after re-authorising. A reasonable answer can be found here: Axios interceptors and asynchronous login
I am pretty new to Axios and very new to OAuth and Firebase, so I'm sure I'm missing something dumb...
I am trying to create a sign in using firebase's auth provider functions & then create a user profile in my database using Axios. (I have to make a ton of other API calls based on the data I receive and it would be very convenient to just use Axios for everything.)
Here is what I have so far.
authenticate() {
var provider = new firebase.auth.GithubAuthProvider();
console.log(provider);
firebase.auth().signInWithPopup(provider)
.then((res) => {
console.log(res);
if (res.credential) {
var token = res.credential.accessToken;
}
const user = axios.create({
baseURL: fbaseUrl,
withCredentials: true, // newly added
headers: {
Authorization: `Bearer ${token}`, // cf firebase docs https://firebase.google.com/docs/reference/rest/database/user-auth
}
});
this.setState({uid: res.user.uid, useraxios: user, token: token});
}).catch((err) => {
console.log(err.message);
});
}
testPost() {
this.state.useraxios.post(`/users.json`, { id: this.state.uid, joinedOn: moment() })
.then((res) => console.log(res))
.catch((err) => console.log(err.message)); /// this errors out
}
The error I'm currently getting is that there is no 'Access-Control-Allow-Credentials' header and therefore localhost is not allowed access, which I assume is something in the Firebase rules that I have to sort through. Before I added the withCredentials: true line, I was just getting the "not allowed access" response.
I have also tried
const user = axios.create({
baseURL: `${fbaseUrl}/users/${res.user.uid}.json?auth=${token}`
});
and
firebase.auth().currentUser.getToken(true).then((token) => {
const user = axios.create({
baseURL: `${fbaseUrl}/users/${res.user.uid}.json?auth=${token}`
});
and
firebase.auth().currentUser.getToken(true).then((token) => {
const user = axios.create({
baseURL: `${fbaseUrl}`,
headers: {Authorization: token}
});
as per this stackoverflow question which returns the 401 Unauthorized error.
Posting to the database is totally fine when I have both read & write set to true, so it's not a problem with how I'm formatting the URL or something.
I am assuming there are a couple of problems, one with my axios.create config and another with my Firebase rules, but I have gone through the documentation for both and am still very much at a loss. This is a react app but I'm 98% sure the react stuff isn't the problem.
Am I at least on the right track? (Am I a fool to try to use axios for something that would be better suited to firebase's built-in methods...?) Any help would be deeply appreciated.
It is related to your functions configuration. You need to add this in your firebase functions / index.js and configure your function with cors.
const cors = require('cors')({origin: true});
For more details please refer to this url: Enabling CORS in Cloud Functions for Firebase