LinkedIn Get Posts API is restricted to partners? - linkedin

I'm making a request to LinkedIn's get posts by post urn endpoint, here my function:
async function getPost(accessToken, postUrn) {
const url = `https://api.linkedin.com/rest/posts/${encodeURIComponent(
postUrn
)}?viewContext=AUTHOR`;
const response = await fetch(url, {
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/x-www-form-urlencoded",
"X-Restli-Protocol-Version": "2.0.0",
"LinkedIn-Version": "202209",
},
});
if (response.status == 200) {
return await response.json();
} else {
console.log(response.status);
console.log(response.statusText);
console.log(await response.json());
throw new Error(JSON.stringify(response));
}
}
The response I get is:
403
Forbidden
{
serviceErrorCode: 100,
code: 'ACCESS_DENIED',
message: 'Not enough permissions to access: partnerApiPosts.GET.20220901'
}
So what's going on? I enabled all the products the were available for the app in the products section (Share on LinkedIn, Sign in with LinkedIn and Marketing Developer Platform) on developers LinkedIn page.
Microsoft documentation doesn't state that this is available only to LinkedIn partners. Is it?

Related

Getting ugcPost details through rest/posts api?

I could not get the ugcPost of a post or comment, the urn looks like: urn:li:ugcPost:7023566176156811264,7023567581345140736
how to use this in the api rest/posts/{ugcPosts urn}
the API returns the error {
"message": "Could not find entity",
"status": 404,
"code": "NOT_FOUND"
}
I have also added the headers
{
Linkedin-Version: 202210,
X-RestLi-Protocol-Version: 2.0.0
}
but it is still returning the same error even though I have encoded the urn, example:
https://api.linkedin.com/rest/posts/urn%3Ali%3AugcPost%3A7023566176156811264?viewContext=Reader
You need to add a bearer token in the header. And viewContext=Reader params is not required as per my knowledge of the documentation. I am sharing a sample example.
var axios = require('axios');
var config = {
method: 'get',
url: 'https://api.linkedin.com/rest/posts/urn%3Ali%3AugcPost%3A7023566176156811264',
headers: {
'X-Restli-Protocol-Version': '2.0.0',
'LinkedIn-Version': '202208',
'Authorization': 'Bearer [your_bearer_token]',
}
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
You can visit this link for more information.

Google Firebase Messaging API facing CORS error

Hi there Guys i'm tryng to subscribe Firebase Cloud Messaging channels with provided token via capacitor/ioni app using PWA. But i got a CORS issue when i publish the www folder, instead on localhost it is working
This is the code im using in .ts file
this.devices = response;
FirebaseMessaging.requestPermissions().then(result => {
if(result.receive === 'granted')
{
FirebaseMessaging.getToken(
{
vapidKey: 'my-vapid-key',
}
).then( result => {
const token = result.token;
this.devices.forEach(i => {
let topic = i.serial
fetch('https://iid.googleapis.com/iid/v1/'+ token +'/rel/topics/'+ topic, {
method: 'POST',
headers: new Headers({
'Access-Control-Allow-Origin': '*',
"Access-Control-Allow-Methods": "DELETE, POST, GET, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization, X-Requested-With",
'Authorization': 'key=my-key'
})
}).then(response => {
alert('Fatto')
if (response.status < 200 || response.status >= 400) {
throw 'Error subscribing to topic: '+response.status + ' - ' + response.text();
}
console.log('Subscribed to "'+topic+'"');
}).catch(error => {
console.error(error);
})
})
this.addReceivedListener();
the error i faced is: "https://iid.googleapis.com/iid/v1/xxxxxxxxtokeeeen/rel/topics/mytopic' from origin 'https://mysite.site.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."
there is no CORS on the other side, so we need to disable it and its working

How to implement Wordpress Application Password Authentication in Javascript async fetch?

I'm trying to setup a website using Wordpress as Headless CMS, using the built-in REST API. Using NuxtJS to fetch the data. Now I want to restrict API access so I enabled/created Wordpress Application Password Authentication.
However, I can not seem to find detailed information on how the URL should be assembled with authentication parameters to fetch data from API endpoint.
Credentials have to be added to the URL that's being fetched?
async asyncData ({ $config: { apiUrl, apiUser, apiPassword } }) {
try {
const products = await (await fetch(`${apiUrl}/producten`)).json()
return {
products
}
}
catch (error) {
console.log(error)
}
},
apiUrl, apiUser, apiPassword are currently in nuxtjs.config.js, under publicRuntimeConfig. But 1) they should come in privateRuntimeConfig?
And 2) getting following as return (which is the correct response from the WP Rest API, because I need to pass auth-credentials somewhere, somehow...)
{ "code": "rest_not_logged_in", "message": "You are not currently logged in.", "data": { "status": 401 } }
Solved by adding options to fetch;
const fetchHeaderOptions = {
cache: 'no-cache',
method: 'GET',
credentials: 'omit', //To instead ensure browsers don't include credentials in the request
mode: 'no-cors',
headers: {
'Authorization': 'Basic ' + encode(`${apiUser}` + ":" + `${apiPassword}`),
'Content-Type': 'application/json; charset=UTF-8; application/x-www-form-urlencoded',
},
}
const products = await (await fetch(`${apiUrl}/products`, fetchHeaderOptions)).json()

Axios post request returning 403 when sending firebase notification

Hi I am trying to send notification to my app using firebase post method its working fine in postman but when I try to do post method in my app its returning 403. I tried implementing another get request its working fine so no problem with axios setup.
export const postData = function (url, payload) {
return AXIOS.post(url, payload, config);
};
let config = {
headers: {
'Content-Type': 'application/json',
"Authorization" : "key= *****myKey****"
}
};
Here is my post mehtod
let body = {
"to": "******myTokeb*******",
"notification": {
"title": "Title here",
"body": "R(body)",
"mutable_content": true,
"sound": "Tri-tone"
}
};
postData("http://fcm.googleapis.com/fcm/send",body).then((d)=>{
console.log("d",d)
}).catch((e)=>{
console.log("e",e);
});
Error
Error: Request failed with status code 403
at createError (D:\projects\fiver\Roeyat\node_modules\axios\lib\core\createError.js:16)
at settle (D:\projects\fiver\Roeyat\node_modules\axios\lib\core\settle.js:17)
at EventTarget.handleLoad (D:\projects\fiver\Roeyat\node_modules\axios\lib\adapters\xhr.js:61)
at EventTarget.dispatchEvent (D:\projects\fiver\Roeyat\node_modules\event-target-shim\dist\event-target-shim.js:818)
at EventTarget.setReadyState (D:\projects\fiver\Roeyat\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:567)
at EventTarget.__didCompleteResponse (D:\projects\fiver\Roeyat\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:389)
at D:\projects\fiver\Roeyat\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:502
at RCTDeviceEventEmitter.emit (D:\projects\fiver\Roeyat\node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:189)
at MessageQueue.__callFunction (D:\projects\fiver\Roeyat\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:425)
at D:\projects\fiver\Roeyat\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:112
Use HTTPS in postData
That will work!

403 The caller does not have permission for Firebase Management API addFirebase

I want to add Firebase project through Firebase Management Api. So for that. I made project on Google Cloud Platform console. And created service account with permission as a owner.
I tried to read and create project throw google api explorer for addFirebase and it works. But when i try to do the same through my code it read availableProject successfully and give output as
{
"projectInfo": [
{
"project": "projects/firebase-api-238012",
"displayName": "Firebase-Api"
}
]
}
but when i try to add project it give me this error
{
"error": {
"code": 403,
"message": "The caller does not have permission",
"status": "PERMISSION_DENIED"
}
}
I don't know why its is not creating project. What other permission it needs. And why it allowed to me read available projects first.
here is how i am trying to add my project.
jwt.js
const { google } = require('googleapis');
var serviceAccountJwt = require('./Firebase-Api-b0e41b85ad44.json');
exports.connect = async () => {
return new Promise((resolve, reject) => {
// scope is based on what is needed in our api
const scope = ['https://www.googleapis.com/auth/firebase', 'https://www.googleapis.com/auth/cloud-platform'];
// create our client with the service account JWT
const { client_email, private_key } = serviceAccountJwt;
const client = new google.auth.JWT(client_email, null, private_key, scope, null);
// perform authorization and resolve with the client
return client.authorize((err) => {
if (err) { reject(err) }
else {
resolve(client)
};
});
});
}
index.js file
const { google } = require('googleapis');
const request = require('request');
const { connect } = require('./jwt');
const availableProjects = 'https://firebase.googleapis.com/v1beta1/availableProjects';
async function getAccessToken() {
let client = await connect();
let accessToken = await client.getAccessToken();
let res = await getProjects(accessToken.token)
}
getAccessToken().catch(err => {
console.log(JSON.stringify(err))
})
const bodys = {
"timeZone": "America/Los_Angeles",
"locationId": "asia-south1",
"regionCode": "US"
}
async function getProjects(accesstoken) {
let options = {
url: availableProjects,
headers: {
'Authorization': 'Bearer ' + accesstoken,
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}
return request(options, async function (err, res) {
if (err) {
console.error(err + " error");
} else {
//here it gives successful output
console.log("response")
console.log(res.body);
let bodyJson = JSON.parse(res.body);
let projectName = bodyJson.projectInfo[0].project;
console.log(projectName)
await addProject(accesstoken, projectName)
return res.body;
}
});
}
async function addProject(accesstoken, projecctID) {
fbUrl = getAddFBUrl(projecctID);
let options = {
url: fbUrl,
headers: {
'Authorization': 'Bearer ' + accesstoken,
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body:JSON.stringify(bodys)
}
return request.post(options, function (err, res) {
if (err) {
console.error(err + " error");
} else {
//here in response out put as permission denied 403
console.log("response")
console.log(res.body);
console.log(JSON.stringify(res));
return res.body;
}
});
}
function getAddFBUrl(projectId) {
return 'https://firebase.googleapis.com/v1beta1/' + projectId +
':addFirebase';
}
i found one similar question to this. But it didn't helped me to resolve my issue which is here
AskFirebase
From the Firebase REST reference: Method: projects.addFirebase
To call projects.addFirebase, a member must be an Editor or Owner for
the existing GCP Project. Service accounts cannot call
projects.addFirebase.
Update:
To call projects.addFirebase, a project member or service account must have the following permissions (the IAM roles of Editor and Owner contain these permissions): firebase.projects.update, resourcemanager.projects.get, serviceusage.services.enable, and serviceusage.services.get.
https://firebase.google.com/docs/projects/api/reference/rest/v1beta1/projects/addFirebase
I'm not sure if my answer will be helpful for author of this question, but this if first two things all should check when facing 403 Error with Google Cloud APIs
0) Check configuration with gcloud
1) As mentioned before the first thing is to check the role of service account. You need Editor/Owner usually.
https://cloud.google.com/iam/docs/understanding-roles
https://console.cloud.google.com/iam-admin
2) The second one is to check if API enabled for project at all.
Also when creating a key check it for correct service account.
For someone who's just get started like me, this thing maybe helpful. When I seted up database, I choose Start in locked mode instead of Start in test mode. Therefore, I can't read or write :((. For beginner, just set everything in test mode. Hope it helpful.
https://i.stack.imgur.com/nVxjk.png
Your problem means that your project is not linked with your firebase account which means you have to login with your firebase account. Than you will have the permission
type cd functions in your firebase project directory
type firebase login
login with the Gmail which is connected with your firebase account
It'll work

Resources