Error 403 when requesting Google APIs in Capacitor - axios

I am working on transferring a Web App into an iOS format using Capacitor. I am using axios to make requests to Google APIs, and my requests return an Error 403 on the iOS version despite working perfectly in the browser.
Here is the flow from authentication to making the first API call (I'm using capacitor-google-auth for the iOS OAuth, then passing the access token I get from that to Axios to use as the header for HTTP requests).
I used these resources so far: https://github.com/CodetrixStudio/CapacitorGoogleAuth, https://developers.google.com/calendar/api/v3/reference/calendarList/list
My plugin settings for GoogleAuth in "capacitor.config.json" (I've also added the URL scheme of the REVERSED_CLIENT_ID to my info.plist file, as the docs for CapacitorGoogleAuth describe):
"plugins": {
"GoogleAuth": {
"scopes": [
"https://www.googleapis.com/auth/calendar"
],
"clientId": <<my iOS Client ID>>
}
}
When starting the app with "index.js," get an access token (works):
import { GoogleAuth } from '#codetrix-studio/capacitor-google-auth'
const axios = require('axios')
const token = await GoogleAuth.signIn()
const response = await axios
.request({
method: 'GET',
url: 'https://www.googleapis.com/calendar/v3/users/me/calendarList',
headers: {
Authorization: `Bearer ${token.authentication.accessToken}`
},
params: {
key: <<My API Key>>
}
})
.catch(err => console.log(err))
console.log(response)
At this point, it throws this error:
{
"message": "Request failed with status code 403",
"name": "AxiosError",
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"transformRequest": [null],
"transformResponse": [null],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"env": { "FormData": null },
"headers": {
"Accept": "application/json, text/plain, */*",
"Authorization": "Bearer <<My access token>>"
},
"method": "get",
"url": "https://www.googleapis.com/calendar/v3/users/me/calendarList",
"params": { "key": <<My Api key>> }
},
"code": "ERR_BAD_REQUEST",
"status": 403
}
Why is this happening with iOS? Is there an issue with the credentials in some way? Do Google APIs not allow HTTP requests from Capacitor apps? Any help would be appreciated as I'm quite stumped. This code works perfectly outside of the iOS environment.

So after reviewing this a bit, I learned that Capacitor apps have HTTP restrictions. Changing my request client to use the Capacitor community HTTP module works.
https://capacitorjs.com/docs/apis/http

Related

Using microsoft graph api to send email from a react application - 401 error

I have a react application that grants access to a user's outlook account. The azure app has delegated permissions for Mail.Send, Mail.ReadWrite and User.Read and when I go through the authorization flow I'm prompted that the application will be able to read and send emails for me. However, after retrieving an access token I get a 401 unauthorized error when sending an email. The logs say the token claims have Mail.Send, Mail.ReadWrite and I'm able to retrieve the user's emails just fine. So I think the token is valid. But sending an email doesn't work and gets a 401 error. Any ideas would be appreciated. Here is my request:
const url = "https://graph.microsoft.com/v1.0/me/sendMail";
const messageToSend = {
subject: "Testing Outlook API",
importance: "Low",
body: {
contentType: "HTML",
content:
"Hello, Testing 1234. This is the body of the message to send. <b>awesome</b>! ",
},
toRecipients: [
{
emailAddress: {
address: "someemail#email.com",
},
},
],
ccRecipients: [
{
emailAddress: {
address: "anotheremail#email.com",
},
},
],
saveToSentItems: true,
};
const headers = {
"Content-Type": "application/json",
Authorization: `Bearer ${microsoftToken}`,
};
axios
.post(url, messageToSend, {
headers: headers,
})
.then((response) => {
console.log("sent mail", response.data);
return response.data;
})
.catch((error) => {
console.log("📛", error);
return false;
});

LinkedIn API :: how to obtain the bearer access token

It's not easy to use the official LinkedIn API and I cannot find a valid documentation.
Following the official documentation I created a new application in order to obtain the Client ID and Client Secret
When I now make a POST call through Postman to https://www.linkedin.com/oauth/v2/accessToken this is what I obtain:
{
"error": "invalid_grant_type",
"error_description": "The passed in grant_type is invalid"
}
Where am I wrong?
EDIT AFTER HELP FROM #Amit Singh
Thanks to #AmitSingh I was able to create 2 different applications, the test with the Client Credentials flow gave me as a result an error retrieving the token:
{
"error": "access_denied",
"error_description": "This application is not allowed to create application tokens"
}
When I try to use the LinkedIn 3-legged workflow I receive Unauthorized
EDIT 3: GETTING THERE THROUGH POSTMAN
I now see that I can ask Postman to do the job, however when I press on Get New Access Token it opens an error page. I believe the error might be in these 4 elements:
Token name: maybe I have to give a special token name?
Auth URL: I set https://www.getpostman.com/oauth2/callback as explained here but maybe I have to set something else?
Access Token URL: I left it blank, maybe I have to put something here?
State: I set a random string like Hello123Boy but maybe I have to put something else. Maybe is too long. Maybe is too short. Maybe it has to contain symbols, etc... ?
...Also, in the guide you linked it says that the applicatoin needs to have:
r_liteprofile
rw_company_admin
w_member_social
mine has nothing:
Being recently created is still under review. It says it can take up to 90 days. Is that true?
4th EDIT: I WANT TO BELIEVE!
Here we are, at least now I'm getting the error: Bummer, something went wrong. The redirect_uri does not match the registered value. This is amazing: finally an error that says where the problem is!
On the app the, on the Products tab, I choose Sign In with LinkedIn. As
Authorized redirect URLs for your app I set https://www.getpostman.com/oauth2/callback
In Postman I setup Auth URL and Access Token URL as you said:
LinkedIn Credential workflows
LinkedIn offers 2 different credential workflows.
LinkedIn 3-legged workflow - When you want to use an API that will access LinkedIn member's data. Authorization Code grant type needed.
LinkedIn Client Credentials flow - When you want to use an API that will access non-member resources. Client credentials grant needed.
What are grant types?
"Grant type" refers to how you have acquired an access token in an OAuth workflow.
Several grant types are supported. Some of them are:
Client Credentials - Used when you want to access your own resources and not any other users
Authorization Code - Used when an app wants to access a client's data
Refresh token - Exchange an expired access token for a valid access token, used to avoid repeated user involvement
Password - Used when there is high trust between the app and the user e.g. LinkedIn mobile app, you provide your username and password
Client Credentials flow
What you need to know
Grant type used here is Client credentials - client_credentials.
Remember to set your Content-Type to application/x-www-form-urlencoded for all POST requests in OAuth.
Steps
Create an App and get your Client ID and Client Secret. Steps are shown in the respective docs linked above. Let's say they have values - <client_id> and <client_secret>.
Send a POST required to https://www.linkedin.com/oauth/v2/accessToken with following information.
Parameters
grant_type : client_credentials
client_id : <client_id>
client_secret : <client_secret>
NOTE : client_credentials is the literal text to be entered for grant_type.
Response will return a JSON Object containing your access token and its expiry duration in seconds.
Response
{
"access_token" : <access_token>,
"expires_in" : "1800"
}
Use the <access_token> obtained in Step 2 make API requests.
Example
Request URL: https://www.linkedin.com/v2/jobs
Request type: GET
Parameters
Authorization: Bearer <access_token>
LinkedIn 3-legged workflow
What you need to know
Grant type will be Authorization code - code, since you want to access a user's data.
Your Content-Type should be application/x-www-form-urlencoded for all POST requests in OAuth.
Redirect URLs are URLs where you OAuth server will redirect the user after successful authorization.
These are verified against your provided redirect URLs to ensure that it's not fraudulent.
These should be absolute URLs.
URL arguments are ignored and cannot include a #.
Steps
Create app and provide the Redirect URLs, if not already provided. Check docs for information regarding how to do this.
Get your Client ID and Client Secret. Let's say the values are <client_id> and <client_secret>.
Generate a random, hard to guess string. Let's say it's <random-string>.
Choose one of the redirect URLs provided in Step 1, where you want user to be redirected after authorization. Let's say it is <redirect_uri>.
Let's suppose you want to:
r_emailaddress - Get his email address
w_member_social - Post, comment and like posts on behalf of the user.
These are referred as "permission scopes", as in what permissions is the user authenticating you for. When sending these scopes in your request, they should be URL-encoded and space-delimited. In this particular instance, our scope will be scope: r_emailaddress%20w_member_social. We have URL-encoded the scopes mentioned above.
Adding more information regarding scopes from the Microsoft docs:
The scopes available to your app depend on which Products or Partner Programs your app has access to. Your app's Auth tab will show current scopes available. You can apply for new Products under the Products tab. If approved, your app will have access to new scopes.
Send a POST request to https://www.linkedin.com/oauth/v2/authorization with following information.
Parameters
response_type : code
client_id : <client_id>
redirect_uri : <redirect_uri>
state : <random_string>
scope : r_emailaddress%20w_member_social
After the request, the user will be presented with LinkedIn's Auth screen and asked to approve the request.
After user approves the request and the <redirect_uri> has been verified, user will be redirected to provided <redirect_uri> along with the access code <access_code> and a value in state argument. Let's say in the state argument is <state_value>.
Verify that the <state_value> is equal to the <random_string> before working with the <access_code> to get access token, for security purposes. Also, use the <access_code> within 30 minutes of being issued, for security reasons.
Next, send a POST request to https://www.linkedin.com/oauth/v2/accessToken with following information to get the access token.
Parameters
grant_type : authorization_code
client_id : <client_id>
client_secret : <client_secret>
redirect_uri : <redirect_uri>
code : <access_code>
NOTE : authorization_code is the literal text to be passed in grant_type.
You should get a similar response as in the Client Credentials workflow containing your access token and expiry duration.
Response
{
"access_token" : <access_token>,
"expires_in" : "1800"
}
Use the <access_token> obtained in Step 9 make API requests.
Example
Request URL: `https://www.linkedin.com/v2/me`
Request type: GET
Parameters:
Authorization: Bearer <access_token>
How to do this in Postman?
Create a new Collection.
Right click, select edit collection and move to authorization tab.
In "Type", select "OAuth2.0", click on "Get New Access Token".
You will see a screen where all the familiar terms mentioned above are there. Fill those, check the "Authorize via Browser" checkbox for authorization.
Now you have the access token and can proceed to make your API calls.
Postman has been designed to make such operations easier, but you have to know how to do it. For more details, you can read their official docs.
Thanks to #timur and #AmitSingh I finally arrived to authenticate to LinkedIn API.
A brief step by step solution in pictures:
Authorized redirect URLs for your app = https://oauth.pstmn.io/v1/callback
OAuth 2.0 scopes = must have r_emailaddress and r_liteprofile
In the Products Tab set Sign In with LinkedIn
Now open Postman > Collections > New Collection > Authorization and set the parameters as in picture:
TYPE = OAUTH 2.0
Token Name = put whatever you want
Callback URL = https://oauth.pstmn.io/v1/callback (should be greyed out once you tick Authorize using browser)
Tick Authorize using browser
Auth URL = https://www.linkedin.com/oauth/v2/authorization
Access Token URL = https://www.linkedin.com/oauth/v2/accessToken
Client ID = The Client ID you find on your LinkedIn App
Client Secret = The Client Secret you find on your LinkedIn App
Scope = r_liteprofile r_emailaddress
State = put whatever you like
Now click on Get New Access Token, a page will open on your browser and you will be able to login using your LinkedIn account. Once done you are authenticated.
Now use the code provided by #timur and on Postman go to Import > Upload File and import that .JSON file. You will now have the 4 queries and you can drag and drop them in your collection.
Assuming you've created your app, added correct redirect URL and enabled "Sign In with LinkedIn" product for your app, the issue you are having is probably that the first call returns a login page where your users are supposed to authenticate.
submit the request to https://www.linkedin.com/oauth/v2/authorization (you seem to have done that)
parse response of step 1 and extract all form values, add username and password to simulate user login
make POST request and use values from previous step as x-www-form-urlencoded data
manually follow the redirect header from step 3
make note of second redirect header but do not follow it - instead extract the code
POST code from previous step to https://www.linkedin.com/oauth/v2/accessToken and get access_token in response
From here, I was able to successfully transition to the auth code by following the steps.
I am not sure if you use the online Postman, but here's my complete collection export file for reference:
{
"info": {
"_postman_id": "397761c9-4287-43f2-860a-3c34cb710d50",
"name": "Linkedin oAuth",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
"name": "01 request Login form",
"event": [
{
"listen": "test",
"script": {
"exec": [
"const $ = cheerio.load(pm.response.text());\r",
"var inputs = $('form').serializeArray();\r",
"var payload = '';\r",
"inputs.forEach(i => {\r",
" payload += encodeURIComponent(i.name)+ '=' + encodeURIComponent(i.value) + '&';\r",
"})\r",
"payload += 'session_key='+ encodeURIComponent(pm.collectionVariables.get('username')) + '&'\r",
"payload += 'session_password='+ encodeURIComponent(pm.collectionVariables.get('password'))\r",
"\r",
"pm.collectionVariables.set(\"form_data\", payload);"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id={{client_id}}&redirect_uri={{redirect_uri}}&scope=r_liteprofile&state={{$guid}}",
"protocol": "https",
"host": [
"www",
"linkedin",
"com"
],
"path": [
"oauth",
"v2",
"authorization"
],
"query": [
{
"key": "response_type",
"value": "code"
},
{
"key": "client_id",
"value": "{{client_id}}"
},
{
"key": "redirect_uri",
"value": "{{redirect_uri}}"
},
{
"key": "scope",
"value": "r_liteprofile"
},
{
"key": "state",
"value": "{{$guid}}"
}
]
}
},
"response": []
},
{
"name": "02 Submit login form",
"event": [
{
"listen": "prerequest",
"script": {
"exec": [
""
],
"type": "text/javascript"
}
},
{
"listen": "test",
"script": {
"exec": [
"var url = 'https://www.linkedin.com'+ pm.response.headers.get(\"Location\");\r",
"pm.collectionVariables.set('first_redirect', url);\r",
"//console.log(pm.collectionVariables.get('first_redirect'));"
],
"type": "text/javascript"
}
}
],
"protocolProfileBehavior": {
"followRedirects": false
},
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/x-www-form-urlencoded",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "{{form_data}}",
"options": {
"raw": {
"language": "text"
}
}
},
"url": {
"raw": "https://www.linkedin.com/checkpoint/lg/login-submit",
"protocol": "https",
"host": [
"www",
"linkedin",
"com"
],
"path": [
"checkpoint",
"lg",
"login-submit"
]
}
},
"response": []
},
{
"name": "03 handle login-success redirect",
"event": [
{
"listen": "test",
"script": {
"exec": [
"var sdk = require('postman-collection');\r",
"var redirect = new sdk.Url(pm.response.headers.get(\"Location\"));\r",
"pm.collectionVariables.set('code', redirect.query.filter(q => q.key === 'code').map(k => k.value)[0]);\r",
"//console.log(pm.collectionVariables.get('code'));"
],
"type": "text/javascript"
}
},
{
"listen": "prerequest",
"script": {
"exec": [
"console.log(pm.variables.get('first_redirect'));\r",
"pm.request.url.update(pm.variables.get('first_redirect'));"
],
"type": "text/javascript"
}
}
],
"protocolProfileBehavior": {
"followRedirects": false
},
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "{{first_redirect}}",
"host": [
"{{first_redirect}}"
]
}
},
"response": []
},
{
"name": "04 Get Auth Code",
"request": {
"method": "POST",
"header": [],
"url": {
"raw": "https://www.linkedin.com/oauth/v2/accessToken?grant_type=authorization_code&code={{code}}&redirect_uri={{redirect_uri}}&client_id={{client_id}}&client_secret={{client_secret}}",
"protocol": "https",
"host": [
"www",
"linkedin",
"com"
],
"path": [
"oauth",
"v2",
"accessToken"
],
"query": [
{
"key": "grant_type",
"value": "authorization_code"
},
{
"key": "code",
"value": "{{code}}"
},
{
"key": "redirect_uri",
"value": "{{redirect_uri}}"
},
{
"key": "client_id",
"value": "{{client_id}}"
},
{
"key": "client_secret",
"value": "{{client_secret}}"
}
]
}
},
"response": []
}
],
"event": [
{
"listen": "prerequest",
"script": {
"type": "text/javascript",
"exec": [
""
]
}
},
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
""
]
}
}
],
"variable": [
{
"key": "client_id",
"value": "your app id"
},
{
"key": "client_secret",
"value": "your app secret"
},
{
"key": "redirect_uri",
"value": "your urlencoded redirect uri such as https%3A%2F%2Flocalhost%3A8080"
},
{
"key": "username",
"value": "user login"
},
{
"key": "password",
"value": "user password"
}
]
}

Google Apps Script doesn't recognize "Host" header in HTTP POST request?

I'm trying to query ArcGIS Rest API from Google Apps script. Building the request in Postman works perfectly fine, but when I get the code into apps script, I'm having trouble that I cant seem to figure out. Here's the code:
function callEsri () {
var url = "https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/Trailheads/FeatureServer/0/query"
var params =
{
"async": true,
"crossDomain": true,
"url": "https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/Trailheads/FeatureServer/0/query",
"method": "POST",
"headers": {
"Content-Type": "application/x-www-form-urlencoded",
"User-Agent": "PostmanRuntime/7.20.1",
"Accept": "*/*",
"Cache-Control": "no-cache",
"Postman-Token": "[TOKEN]",
"Host": "services3.arcgis.com",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "125",
"Connection": "keep-alive",
"cache-control": "no-cache"
},
"data": {
"f": "json",
"where": "CITY_JUR LIKE '%Los Angeles%'",
"outSr": "4326",
"outFields": "TRL_NAME,ELEV_FT,CITY_JUR,PARK_NAME,FID"
}
}
var response = UrlFetchApp.fetch(url, params);
var json = response.getContentText();
var data = JSON.parse(json);
Logger.log(data);
}
The Error I am getting is: Execution failed: Attribute provided with invalid value: Header:Host (line 28, file "Code")
Any reason why Google is not recognizing this and is there a way to fix this? Any help/advice is greatly appreciated.
As #TheMaster has already noted in the comments. You are already specifying the Host in the url.
Also you can take a look at the official documentation of URLFetchApp.
And in case you want more information in the head here you have the mozilla documentation on that header and also the RFC specifying the Host header.

How I can get authentication token or do loging in Elastic Search using REST API? For example from POSTMAN

I'm trying to list data from Elastic Search using the REST API on Postman.
But I get a security_exception error
I read the elastic documentation at https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-get-token.html
but didn't work.
I'm using Elastic 7.2
Method: POST
Content-type: Application/json
URI: http://xxx.xxx.xxx.xxx:9200/_security/oauth2/token
BODY:
{
"grant_type" : "password",
"username" : "user_name",
"password" : "correct_password"
}
I need this service to return the authentication token. But this is the response:
{
"error": {
"root_cause": [
{
"type": "security_exception",
"reason": "missing authentication credentials for REST request [/_security/oauth2/token]",
"header": {
"WWW-Authenticate": "Basic realm=\"security\" charset=\"UTF-8\""
}
}
],
"type": "security_exception",
"reason": "missing authentication credentials for REST request [/_security/oauth2/token]",
"header": {
"WWW-Authenticate": "Basic realm=\"security\" charset=\"UTF-8\""
}
},
"status": 401
}
Try to do a basic authentication instead. And pass in the body just the grant_type.

Simulator keeps replying that endpoint could not be called, while I see a POST request in the logs

I am currently writing an integration into Actions on Google using PHP. I have generated a action.json file with my test endpoint as the fulfillment. I use ngrok to expose my local development machine publicly.
Unfortunately the simulator keeps insisting that the app isn't responding. In the access logs, and the ngrok Inspector I do see that a request came in, and it has been neatly answered with a JSON reply.
In an act of pure desperation I even upload a JSON response, directly taken from the Fulfillment documentation page to a server and set that as the fulfillment URL. The result is the same, same error.
I do not see a way to get a more detailed error message from Actions on Google, explaining why it does not work.
My action.json:
{
"actions": [
{
"name": "MAIN",
"intent": {
"name": "actions.intent.MAIN"
},
"fulfillment": {
"conversationName": "development4"
}
},
{
"name": "TEXT",
"intent": {
"name": "actions.intent.TEXT"
},
"fulfillment": {
"conversationName": "development4"
}
}
],
"conversations": {
"development4": {
"name": "development4",
"url": "https:\/\/02c085c0.ngrok.io\/actionsongoogle\/process\/development4"
}
}
}
The json I response with:
{
"expectUserResponse": false,
"expectedInputs": [{
"inputPrompt": {
"richInitialPrompt": {
"items": [{
"simpleResponse": {
"textToSpeech": "hello"
}
}]
}
},
"possibleIntents": [{
"intent": ["actions.intent.TEXT"]
}]
}]
}
The result output in the Simulator then displays:
{
"response": "my test app isn’t responding right now. Try again soon.\n",
"audioResponse": "//NExAARq...",
"debugInfo": {
"sharedDebugInfo": [
{
"name": "ExecutionResponse",
"debugInfo": "Failed to call your endpoint."
}
]
},
"visualResponse": {}
}
Two things to investigate:
Check how long it is taking for the reply to be sent. Agents need to send a response back within about 5 seconds or the Assistant will time out and give the "not responding" message.
Check what the reply code being issued is. If you think you're sending something back, but your server actually crashes before an HTTP 200 response code is sent back with the body, the Assistant never gets the response. I've also seen it where people are thinking they're sending a response - but no response is actually sent at all.
Testing with curl or wget to your ngrok URL (so it makes a full round trip) might be able to help diagnose both of these.
The issue was in the returned JSON. I have set up the nodejs SDK and reply in the same way as the PHP cod will (a simple hello). The response generated by the NodeJS SDK is very different. Apparently the example that I used from the docs earlier is also invalid.
I advice anyone building their own implementation using Webhooks to first generate the desired response via de NodeJS sdk, the reference in the manual is not always clear (at least for me).
Response by NodeJS SDK:
{
"expectUserResponse": false,
"finalResponse": {
"speechResponse": {
"textToSpeech": "hello"
}
}
}
Implementation in SDK:
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(function (req, res) {
let ActionsSdkApp = require('actions-on-google').ActionsSdkApp;
const actionsApp = new ActionsSdkApp({request: req, response: res});
//const inputPrompt = actionsApp.buildInputPrompt(false, 'hello')
actionsApp.tell('hello');
})
app.listen(80);