How to set a custom header in Google Cloud Endpoints Javascript Client? - javascript

I can fetch a list of blog posts from Google Cloud Endpoints using the Javascript Client:
gapi.client.blog.posts.list().execute(function (resp) {
console.log(resp);
});
But I need to set a custom header value in the Google Cloud Endpoints request that contains a user token (this could be an access token from Facebook). How can I do that using the Javascript Client from Google? I could solve this by not using the Javascript Client from Google, but I would rather use it.
https://developers.google.com/appengine/docs/java/endpoints/consume_js
https://developers.google.com/api-client-library/javascript/reference/referencedocs
edit
It seems I can pass the custom header value like this:
gapi.auth.setToken({
access_token: 'this is my custom value'
});
Doesn't seem good practice though. Is there a better way to do this?

You can now do this using gapi.client.request, for example:
gapi.client.init({
'clientId': 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com',
'scope': 'your_scope'
}).then(function() {
return gapi.client.request({
'path': 'http://path/to/your/endpoints/api',
'headers': { 'mycustomheader': 'myvalue' }
})
}).then(function(response) {
console.log(response.result);
}, function(reason) {
console.log('Error: ' + reason.result.error.message);
});
See also the Getting Started page of the Google API Javascript Client documentation.

Try using the header normally, but fetching the token and adding a variable containing it where you need the token to show.

Related

How do I make an API call server side?

I've created a client-side application that makes an API call. The issue with this, however, is that in order to make the API call, I have to use an API Key. If I make the call client-side, the user will be able to see the API key. How do I avoid this? Well, if the answer is to call the API server-side, how do I do that? There seems to be little information wherever I look regarding server-side programming, and if anyone could lead me in the right way, it would be great.
You have to set it in the header with bearer
let config = {
headers: {
'Authorization': 'Bearer ' + KEY
}
};
Axios.get('http://url', {}, config )
.then( (response) => {
console.log(response)
})
.catch();

Linkedin webhooks event subscription not working

I've been stuck on this issue for some time now, I am trying to subscribe to Linkedin's webhook using ngrok for testing on localhost, and have been trying for some time now, i have tried using encode uri's as well but still running into error, I have verified that the APP_ID, profileId and organizationId i'm using are correct, but still i get the same error. I have also tried using the Restli protocol that linkedin suggests in their documentation but to no avail.
let url = `https://api.linkedin.com/v2/eventSubscriptions/(developerApplication:urn:li:developerApplication:${config.IN.APP_ID},user:urn:li:person:${profileId},entity:urn:li:organization:${organizationId},eventType:ORGANIZATION_SOCIAL_ACTION_NOTIFICATIONS)`;
return new Promise((resolve, reject) => {
request(
{
url,
method: 'PUT',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`,
// 'X-Restli-Protocol-Version': '2.0.0',
},
json: {
webhook: "https://url.ngrok.io/api/v1/webhook/linkedin/callback"
},
},
(err, response, body) => {
if (err) {
reject(err);
} else {
resolve(body);
}
},
);
});
I have been receiving this error constantly no matter what I try, I have tried sending the url like this:
https://api.linkedin.com/v2/eventSubscriptions/(developerApplication:urn:li:developerApplication:{${config.IN.APP_ID}},user:urn:li:person:{${profileId}},entity:urn:li:organization:{${organizationId}},eventType:ORGANIZATION_SOCIAL_ACTION_NOTIFICATIONS)
https://api.linkedin.com/v2/eventSubscriptions/${encodeURIComponent((developerApplication:urn:li:developerApplication:${config.IN.APP_ID},user:urn:li:person:${profileId},entity:urn:li:organization:${organizationId},eventType:ORGANIZATION_SOCIAL_ACTION_NOTIFICATIONS))
All I receive is this error
'{"serviceErrorCode":100,"message":"Unpermitted fields present in RESOURCE_KEY: Data Processing Exception while processing fields [/key]","status":403}'
Any help would be appreciated, I have been stuck on this for a while now.
The request seems to be OK , but the method should be GET (not PUT)
One thing is to check which ID are you using for application_id. The application ID is the one in the url - https://www.linkedin.com/developers/apps/<id from here>/settings
. You need to use and uncomment the header for Restli.
I'd say that your url needs to look like this, as this is from their original POSTMAN collection.
https://api.linkedin.com/v2/eventSubscriptions/(developerApplication:urn%3Ali%3AdeveloperApplication%3A{{application_id}},user:urn%3Ali%3Aperson%3A{{person_id}},entity:urn%3Ali%3Aorganization%3A{{organization_id}},eventType:ORGANIZATION_SOCIAL_ACTION_NOTIFICATIONS)
You can validate here, their full collection - https://www.postman.com/linkedin-developer-apis/workspace/e781b3ac-4101-4d60-8981-afcb4812623d/request/16069442-9d0bf046-ea81-4af0-9515-d07246a0ab39
LinkedIn webhooks does not support ngrok URIs

How to authenticate an app or organization of Azure DevOps on a SharePoint page (except PAT method) in JavaScript/Jquery?

I want get authentication token using REST API or session based authentication for an app or organization of Azure DevOps on SharePoint webpart page. I want some other ways to authenticate REST API of an organization except Personal Access Token (PAT) method. Can you please help me to give a solution of it? If possible please provide an example/demo of it in JavaScript/JQuery.
I had added an example in which I am using personal Access Token (PAT) to get Projects of an organization
on a SharePoint page
var PATToken = 'xxxx7xxxx6xxxxx7xxxxxxx2xxx';//user need to replace his Personal Access Token here and run this snippent on SharePoint Page.
var orgName = 'TestRaju';
getOrgProjects(orgName);
function getOrgProjects(orgName) {
$.ajax({
url: 'https://dev.azure.com/' + orgName + '/_apis/projects?api-version=5.1',
dataType: 'json',
headers: {
'Authorization': 'Basic ' + btoa("" + ":" + PATToken)
}
}).success(function (results) {
console.log(results);
}).error(function (error) {
console.log(error);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You may try OAuth token:
https://learn.microsoft.com/en-us/azure/devops/integrate/get-started/authentication/oauth?view=azure-devops
User Authorizes your Application
At a high-level, you call the "authorize" endpoint and provide a callback. The callback must be a secure url (https) in your application:
https://app.vssps.visualstudio.com/oauth2/authorize
?client_id={app ID}
&response_type=Assertion
&state={state}
&scope={scope}
&redirect_uri={callback URL}
Assuming the user accepts the authorization, Azure DevOps redirects to your callback location with the authorization code in the URL.
https://fabrikam.azurewebsites.net/myapp/oauth-callback
?code={authorization code}
&state={state}
You may refer to the following case:
Access Azure DevOps REST API with oAuth

Invalid input response and secret when verifying google reCaptcha

I am really struggling to get a successful response when doing a post request to the google recaptcha api. I am receiving the following response:
{
"success": false,
"error-codes": [
"invalid-input-response",
"invalid-input-secret"
]
}
I had a look at reCAPTCHA - error-codes: 'missing-input-response', 'missing-input-secret' when verifying user's response (missing details on POST) and followed the answer as closely as possible but with no success.
Here is my file below:
var request = require('request');
module.exports = {
verifyCaptcha: function(req, res) {
var secret = 'SECRET_KEY';
var response = JSON.stringify(req.body.response);
request({
url: 'https://www.google.com/recaptcha/api/siteverify',
method: 'POST',
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: `secret=${secret}&response=${response}`,
}, function (err, response, body) {
if (err) {
res.status(500).send({
error: "Could not verify captcha"
});
} else {
res.status(200).send({
message: body
});
}
});
},
}
If anyone has a solution to this problem please let me know!
Due to the docs: https://developers.google.com/recaptcha/docs/verify
invalid-input-secret: The secret parameter is invalid or malformed.
Maybe you have mixed the site_key and the secret_key.
You need to add the user remote IP address.
var user_ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
request({
url: 'https://www.google.com/recaptcha/api/siteverify',
method: 'POST',
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: `secret=${secret}&response=${response}&remoteip=${user_ip}`}...
Another thing I see that you are not using template literal, you should change the quotes to ` instead of '.
OR, You should use a ready-made module for reCaptcha, like this one:
https://www.npmjs.com/package/recaptcha
For reCAPTCHA Enterprise, check the official docs: https://cloud.google.com/recaptcha-enterprise/docs/create-assessment.
In short, you need to use the library that Google provides:
const { RecaptchaEnterpriseServiceClient } =
require('#google-cloud/recaptcha-enterprise');
const client = new RecaptchaEnterpriseServiceClient();
const [ response ] = await client.createAssessment({...});
RecaptchaEnterpriseServiceClient requires a service account to be created beforehand as described here. The key for that account with the right roles set can then be read by the app. Check the arguments of the constructor to see the available options to pass the data if the file cannot be retrieved automatically.
var response = JSON.stringify(req.body.response);
The stringifying here is probably the cause of the invalid-input-response error.
If your body is something like {"g-recaptcha-response": "..."}, you need to pull out the response value and pass that directly in your post.
Regarding invalid-input-secret, if you have set up your key and secret through the classic interface at https://www.google.com/u/1/recaptcha/admin/create, then you shouldn't have a problem.However if you set up a key with recaptcha Enterprise on Google Cloud, then it requires that you do Oauth authentication to the Google Cloud API and then use the create.assessment endpoint to get back information on the validity of the user. As Yuuhn implied, the Google provided library makes interaction with recaptcha Enterprise easier, without a lot of documentation digging to find where your REST API calls need to go.

User credentials required: Google Cloud Print Submit API

I am trying to access the Submit API that is apart of the Google Cloud Print however I am running into the error "User credentials required".
I am able to get all the way through authentication and am able to retrieve my access token. I was following this guide https://developers.google.com/cloud-print/docs/appDevGuide
I do not know where it is going wrong. Does anyone know where the credentials are supposed to be inputted?
Here is my code for this portion:
function submitPrintJob(token){
try{
var params = {'printerid':'PRINTER_ID','title':'Test Print Job','ticket':{"version": "1.0", "print": {}},'contentType':'application/pdf'};
var response = https.post({
url: 'https://www.google.com/cloudprint/submit',
body: params,
headers: {'Authorization':'Bearer ' + token}
});
log.debug('submitPrintJob','Response - ' + response.body);
}catch(e){
log.error('submitPrintJob','Error - ' + e.message);
}
}
This code is being in done in Netsuite which is where the https.post API is coming in. I also am aware that I am not sending a document through but I at least need to get past this step. I am getting this error using Postman as well.
Editing to add the portion where I get the token:
I send a request to: https://accounts.google.com/o/oauth2/v2/auth
Parameters:
response_type: code,
scope: https://www.googleapis.com/auth/cloud-platform.read-only,
state: state_parameter_passthrough_value,
redirect_uri: scriplet url
client_id: client id
Google oauth returns a authorization code. I exchange the code for a token this way:
function getToken(code){
try{
var params = {'code':code,'client_id':CLIENT_ID,'client_secret':CLIENT_SECRET,'redirect_uri':REDIRECT_URI,'grant_type':'authorization_code'}
var response = https.post({
url: 'https://www.googleapis.com/oauth2/v4/token',
body: params,
headers: {'Content-Type':'application/x-www-form-urlencoded'}
});
var token = response.body.access_token;
submitPrintJob(token);
}catch(e){
log.error('getAuthCode','Error - ' + e.message);
}
}
As I thought, the problem is how you are getting the access token. In order to get a valid access token to do your cloud print business, you need to include the proper scope. That means that your params object should like like this:
var params = {'code':code,'client_id':CLIENT_ID,'client_secret':CLIENT_SECRET,'redirect_uri':REDIRECT_URI, 'scope': 'https://www.googleapis.com/auth/cloudprint', 'grant_type':'authorization_code'}
This should give you a valid access token to interact with Google Cloud Print. I hope it helps!

Categories

Resources