How to Properly Authenticate Google Vision API Using Polymer - polymer-2.x

I am trying to run a test on the Google Cloud Vision API to see how it fares to the client side Shape Detection API.
I am hoping to POST JSON with a base64 encoded image and get image text and barcodes returned.
I have created a GCP project and API key per the tutorial at (https://cloud.google.com/vision/docs/before-you-begin), but am getting an 401 error when trying to make requests.
error: {code: 401,…}
code: 401
message: "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project."
status: "UNAUTHENTICATED"
The request is written in Polymer 2.x as follows:
<iron-ajax id="googleApi"
body="[[request]]"
content-type="application/json"
handle-as="json"
headers$='{"Authorization": "Bearer [[GOOGLE_API_KEY]]"}'
last-response="{{response}}"
loading="{{loading}}"
method="post"
url="https://vision.googleapis.com/v1/images:annotate">
</iron-ajax>
...
GOOGLE_API_KEY: {
type: String,
value: 'AIza0101010110100101101010'
}
...
getRequest(image) {
let encoded = image.toString('base64');
this.request = {
"requests": [{
"image": {
"content": encoded
},
"features": [{
"type": "LABEL_DETECTION",
"maxResults": 1
}]
}]
};
let request = this.$.googleApi.generateRequest();
request.completes.then(req => {
console.log('submission complete');
console.log(this.response);
})
.catch(error => {
console.log(error);
})
}
How do I resolve this authentication error?
It is an account admin issue? Improperly formatted code?

The authorization header is not needed, so the request should be in the form of:
<iron-ajax id="googleApi"
body="[[request]]"
content-type="application/json"
handle-as="json"
last-response="{{response}}"
loading="{{loading}}"
method="post"
url="https://vision.googleapis.com/v1/images:annotate?key=[[GOOGLE_API_KEY]]">
</iron-ajax>

Related

Authenticate a cognito user using expo AuthSession API

I am using this example code
I am able to get a response from authorize endpoint.
request: {"clientId": "<retracted>", "clientSecret": undefined, "codeChallenge": "t6xISsEiAwOIwQxk0Ty1JNo2Kqa53mECL9a7YahLv_A", "codeChallengeMethod": "S256", "codeVerifier": "<retracted>", "extraParams": {}, "prompt": undefined, "redirectUri": "exp://192.168.0.22:19000", "responseType": "code", "scopes": undefined, "state": "o7FeO9ANoa", "url": "https://<retracted>"//oauth2/authorize?code_challenge=t6xISsEiAwOIwQxk0Ty1JNo2Kqa53mECL9a7YahLv_A&code_challenge_method=S256&redirect_uri=exp%3A%2F%2F192.168.0.22%3A19000&client_id=<retracted>"f&response_type=code&state=o7FeO9ANoa", "usePKCE": true}
LOG response: {"authentication": null, "error": null, "errorCode": null, "params": {"code": "<retracted>"", "state": "o7FeO9ANoa"}, "type": "success", "url": "exp://192.168.0.22:19000?code=<retracted>"&state=o7FeO9ANoa"}
const exchangeFn = async (exchangeTokenReq) => {
try {
const exchangeTokenResponse = await exchangeCodeAsync(
exchangeTokenReq,
discoveryDocument
);
setAuthTokens(exchangeTokenResponse);
} catch (error) {
console.error(error);
}
};
while exchangeFn is being invoked i am getting an error "ERROR [Error: Client authentication failed (e.g., unknown client, no client authentication included, or unsupported authentication method). The authorization server MAY return an HTTP 401 (Unauthorized) status code to indicate which HTTP authentication schemes are supported. If the client attempted to authenticate via the "Authorization" request header field, the authorization server MUST respond with an HTTP 401 (Unauthorized) status code and include the "WWW-Authenticate" response header field matching the authentication scheme used by the client.]"
Here is the application flow enter image description here
As per Oauth 2.0 while Exchanging an authorization code grant with PKCE for tokens we need to add Authorization header.
The authorization header string is Basic Base64Encode(client_id:client_secret). The following example is an authorization header for app client djc98u3jiedmi283eu928 with client secret abcdef01234567890, using the Base64-encoded version of the string djc98u3jiedmi283eu928:abcdef01234567890
The example code does not include this. That is the issue. we have to get the App client secret from aws cognito and add it to exchangeTokenReq.
const clientId = '<your-client-id-here>';
const userPoolUrl =
'https://<your-user-pool-domain>.auth.<your-region>.amazoncognito.com';
const redirectUri = 'your-redirect-uri';
const clientSecret = 'app-client-secret';
exchangeFn({
clientId,
code: response.params.code,
redirectUri,
clientSecret,
extraParams: {
code_verifier: request.codeVerifier,
},
});

Attempting to subscribe to a Shopify Webhook w/AWS EventBridge produces error: "Address is an AWS ARN and includes api_client_id 'x' instead of 'y'"

I'm running this request through Postman. Some posts to the Shopify developer forum (e.g., this one) express without clear explanation that the request should be made within the Shopify app that would be subscribing to the Webhooks, but Postman seems to work, too.
In Postman . . .
Here's the endpoint:
https://{{shopifyDevelopmentStoreName}}.myshopify.com/admin/api/2022-07/graphql.json
Here's the GraphQL body:
mutation createWebhookSubscription($topic: WebhookSubscriptionTopic!, $webhookSubscription: EventBridgeWebhookSubscriptionInput!) {
eventBridgeWebhookSubscriptionCreate(
topic: $topic,
webhookSubscription: $webhookSubscription
) {
webhookSubscription {
id
}
userErrors {
message
}
}
}
Here's the payload being sent (notice the "client_id_x" value within the arn property):
{
"topic": "PRODUCTS_CREATE",
"webhookSubscription": {
"arn": "arn:aws:events:us-east-1::event-source/aws.partner/shopify.com/client_id_x/LovecraftEventBridgeSource",
"format": "JSON",
"includeFields": "id"
}
}
Here's the response I receive:
{
"data": {
"eventBridgeWebhookSubscriptionCreate": {
"webhookSubscription": null,
"userErrors": [
{
"message": "Address is invalid"
},
{
"message": "Address is an AWS ARN and includes api_client_id 'client_id_x' instead of 'client_id_y'"
}
]
}
},
"extensions": {
"cost": {
"requestedQueryCost": 10,
"actualQueryCost": 10,
"throttleStatus": {
"maximumAvailable": 1000.0,
"currentlyAvailable": 990,
"restoreRate": 50.0
}
}
}
}
What's entirely unclear is why Shopify is insisting upon validity of "client_id_y" when, in AWS, the value being displayed is undeniably 'client_id_x'. Extremely confusing. I don't even see what difference using the Shopify app would make except that it produces a client_id value that works counter to one's expectations and intuitions.
Does anyone know why the heck Shopify isn't just using the client_id value of the event bus created earlier in Amazon EventBridge?
Same happend to me and I was lucky to find a solution.
The error message is just missleading.
I replaced the API Access Token for the Shopify Rest API Request (X-Shopify-Access-Token)
with the one from the Shopify App holding the aws credentials.
admin/settings/apps/development -> app -> API credentials -> Admin API access token. (can only be seen after creation)
Then I could subscribe webhooks to the app via the Rest Interface.

HTTP Response Error with Post to LinkedIn using Share API v2

I am trying to post a Share to LinkedIn using OAuth v2 - I have got authorisation correctly and have the appropriate access keys.
This code is supposed to share a link on LinkedIn, but for some reason it's not working - I'm not sure why. Can anyone help?
this is my request body:
{
"distribution": {
"linkedInDistributionTarget": {}
},
"owner": "urn:li:person:XXXXXX",
"subject": "Test Share Subject",
"text": {
"text": "Hello !"
}
And this my call API shares :
publishPostLink(body : any, token : any){
this.headers = new HttpHeaders(
{
'Content-Type': 'application/json',
'Authorization':'Bearer '+token,
'cache-control': 'no-cache',
'X-Restli-Protocol-Version':'2.0.0', });
return this.http.post("https://api.linkedin.com/v2/shares" , body, {headers: this.headers});}
I get this issue:
I've already installed the Moesif CORS and it didn't worked
I fixed the error using this post..
it should use REST API from the backend and not from frontend
http://localhost is an insecure request origin so its not supportted in many cases.
Try using tunneling software like Ngork https://ngrok.com/

Invalid Authentication Token when using Microsoft OneDrive REST API

I'm trying to integrate my app with OneDrive. I'm following this tutorial: https://learn.microsoft.com/en-us/onedrive/developer/rest-api/getting-started/?view=odsp-graph-online For oauth I'm using Azure AD v2.0 endpoint.
To get the access token, I'm calling https://login.microsoftonline.com/common/oauth2/v2.0/token and it successfully answers with some json:
{ token_type: 'Bearer',
scope: 'onedrive.readwrite',
expires_in: 3600,
ext_expires_in: 3600,
access_token: '...',
refresh_token: '...' }
When using the access_token that I received to call https://graph.microsoft.com/v2.0/me/drive/root/delta, I get this response:
{
"error": {
"code": "InvalidAuthenticationToken",
"message": "CompactToken parsing failed with error code: 8004920A",
"innerError": {
"request-id": "5eda75b0-c2d5-467f-a728-8006490c00b2",
"date": "2019-08-19T15:56:10"
}
}
}
This error is pretty cryptic and for the life of me I can't work out why that token won't work with this endpoint. Can someone help?
Never mind -- needed to set the scope as files.readwrite.all instead of onedrive.readwrite

GCM Unauthorized Error 401

I'm not able to get response from GCM even i'm providing correct server API key generated by google.
Problem : I want to make a push notification using GCM from my sails app.
I'm posting below code to "https://android.googleapis.com/gcm/send"
Code : 1
{
"headers":{
"Content-Type":"application/json",
"Authorization":"key=xxxxxxxxxxxxxxxxxxxx"
},
"notification":{
"title":"Hello Notify",
"text":"Notification By Sails"
},
"registration_ids":["xxxxxxxxxxxx","xxxxxxxxxxxx","xxxxxxxxxxxx"]
}
Code : 2
{
"headers":{
"Content-Type":"application/json",
"Authorization":"key=xxxxxxxxxxxxxxxxxxxx"
},
"body":{
"notification":{
"title":"Hello Notify",
"text":"Notification By Sails"
}
},
"registration_ids":["xxxxxxxxxxxx","xxxxxxxxxxxx","xxxxxxxxxxxx"]
}
I'm getting response as below.
"statusCode": 401,
"body": "<HTML>\n
<HEAD>\n<TITLE>Unauthorized</TITLE>\n</HEAD>\n
<BODY BGCOLOR=\"#FFFFFF\" TEXT=\"#000000\">\n
<H1>Unauthorized</H1>\n
<H2>Error 401</H2>\n
</BODY>\n
</HTML>\n",
The headers should be HTTP headers, not element in the payload.
Make sure you have enabled the right API in Cloud Console. If sending with a Server API key, you need to have "Google Cloud Messaging for Android" enabled.