Salesforce making REST calls using access token uses local host rather instance url - rest

I am using a ionic app and have implemented oauth using forcejs described here https://github.com/ccoenraets/forcejs/blob/master/README.md
my code looks like below:
getContacts(){
let service = DataService.getInstance();
service.query('select id, Name from contact LIMIT 50')
.then(response => {
let contacts = response.records;
console.log(JSON.stringify(contacts))
});
}
login(){
let oauth = OAuth.createInstance('mycousmerappid','','http://localhost:8100/tabs/tab1');
oauth.login().then(oauthResult => {
DataService.createInstance(oauthResult);
console.log("Logged Into Salesforce Successfully:::" + JSON.stringify(oauthResult));
this.getContacts()
});
}
the oauth token instance url and refresh token all comes up in login but get contact throws error as below
zone-evergreen.js:2952 GET http://localhost:8100/tabs/services/data/v41.0/query?q=select%20id%2C%20Name%20from%20contact%20LIMIT%2050 404 (Not Found)
scheduleTask # zone-evergreen.js:2952
scheduleTask # zone-evergreen.js:378
onScheduleTask # zone-evergreen.js:272
core.js:9110 ERROR Error: Uncaught (in promise): XMLHttpRequest: {"__zone_symbol__readystatechangefalse":[{"type":"eventTask","state":"scheduled","source":"XMLHttpRequest.addEventListener:readystatechange","zone":"angular","runCount":8}],"__zone_symbol__xhrSync":false,"__zone_symbol__xhrURL":"http://localhost:8100/tabs/services/data/v41.0/query?q=select%20id%2C%20Name%20from%20contact%20LIMIT%2050","__zone_symbol__xhrScheduled":true,"__zone_symbol__xhrErrorBeforeScheduled":false,"__zone_symbol__xhrTask":{"type":"macroTask","state":"scheduled","source":"XMLHttpRequest.send","zone":"angular","runCount":0}}
at resolvePromise (zone-evergreen.js:797)
at resolvePromise (zone-evergreen.js:754)
at zone-evergreen.js:858
at ZoneDelegate.invokeTask (zone-evergreen.js:391)
at Object.onInvokeTask (core.js:34182)
at ZoneDelegate.invokeTask (zone-evergreen.js:390)
at Zone.runTask (zone-evergreen.js:168)
at drainMicroTaskQueue (zone-evergreen.js:559)
at ZoneTask.invokeTask [as invoke] (zone-evergreen.js:469)
at invokeTask (zone-evergreen.js:1603)
based on link i am not expecting it to use the base url localhost. Please advise how to fix this issue

i dont know how to resolve the same way but then i used direct http rest format using the accessToken and instanceUrl coming from oAuth. That works just fine

Related

authlib.jose.errors.InvalidClaimError: invalid_claim: Invalid claim "iss"

I'm building an oauth2 client with Flask and Authlib. My code to register the oauth is:
google = oauth.register(
name='google',
client_id='',
client_secret="",
access_token_url="https://accounts.google.com/o/oauth2/token",
access_token_params=None,
authorize_url="https://accounts.google.com/o/oauth2/auth",
authorize_params=None,
api_base_url="https://www.googleapis.com/oauth2/v1/",
client_kwargs={'scope': 'openid email'},
server_metadata_url="https://accounts.google.com/.well-known/openid-configuration",
)
And my /authorize endpoint looks like this:
#app.route('/authorize')
def authorize():
google = oauth.create_client('google')
token = google.authorize_access_token()
resp = google.get('userinfo')
resp.raise_for_status()
userinfo = resp.json()
return str(userinfo)
But I am getting the error
authlib.jose.errors.InvalidClaimError: invalid_claim: Invalid claim "iss"
I had this issue and removing the openid value from scope fixed it. I guess my google config didn't accomodate it,

How to access custom header from AWS Lambda Authorizer?

I have created an Authorizer in AWS API Gateway. This Authorizer refers to a Lambda Function.
I am passing the following values in header, to the API Endpoint using Postman.
{
"type":"TOKEN",
"authorizationToken": "testing2",
"methodArn": "arn:aws:execute-api:us-west-2:444456789012:ymy8tbxw7b/*/GET/"
}
The above header values are received in the Lambda Function. I can see this through the logs in CloudWatch.
I want to pass additional value 'clientID' in the header. So I pass the following values in the header from postman.
{
"type":"TOKEN",
"authorizationToken": "testing2",
"methodArn": "arn:aws:execute-api:us-west-2:123456789012:ymy8tbxw7b/*/GET/",
"clientID" : "1000"
}
In this case, the Lambda function does not get the clientID. I checked various threads in SO, and understood that this can be achieved mapping header. So I did the following.
In the "Method Execution" section of the API method, I created a new header clientID. In the "Integration Request" section, under "HTTP Headers" section I provided the following value
Name: clientID
Mapped from: method.request.header.clientID
After doing the above, I deployed the API and tried to call the method from Postman, but the clientID is shown undefined. Following is the code that I have written in Lambda Function
exports.handler = function(event, context, callback) {
var clientid = event.clientID;
//I always get event.clientID undefined
console.log("The client ID is:" + event.clientID);
}
EDIT
Following is the error from the CloudWatch Log.
START RequestId: 274c6574-dea5-4009-b777-a929f84b9a9d Version: $LATEST
2019-09-19T09:40:25.944Z 274c6574-dea5-4009-b777-a929f84b9a9d INFO The client ID is:undefined
2019-09-19T09:40:25.968Z 274c6574-dea5-4009-b777-a929f84b9a9d ERROR Invoke Error
{
"errorType": "Error",
"errorMessage": "Unauthorized",
"stack": [
"Error: Unauthorized",
" at _homogeneousError (/var/runtime/CallbackContext.js:13:12)",
" at postError (/var/runtime/CallbackContext.js:30:51)",
" at callback (/var/runtime/CallbackContext.js:42:7)",
" at /var/runtime/CallbackContext.js:105:16",
" at Runtime.exports.handler (/var/task/index.js:40:4)",
" at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)",
" at process._tickCallback (internal/process/next_tick.js:68:7)"
]
}
I have understood why I was not getting the value in the header. I have done the following
1) Instead of type TOKEN, I used type REQUEST in the header. I understood this by reading the following link. This link also contains code for Request type.
https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html
2) I removed all the mapping from Method Request and Integration Request.
3) Deployed the API.

GitHub Probot : ERROR probot: Bad Request

I am developing an application for Probot. I have configured .envand already downloaded PEM file in the folder.
Here is the content of file index.js.
module.exports = (robot) => {
robot.on('issues.opened', async context => {
const params = context.issue({ body: 'Hello World!' })
return context.github.issues.createComment(params)
})
}
But I am getting this error.
ERROR probot: Bad Request
Error: Bad Request
at Request.callback (/media/ashutosh/ASHUTOSH ( PERSONAL )/Gsoc/probot/practice/ashutosh-probot/node_modules/superagent/lib/node/index.js:696:15)
at IncomingMessage.parser (/media/ashutosh/ASHUTOSH ( PERSONAL )/Gsoc/probot/practice/ashutosh-probot/node_modules/superagent/lib/node/index.js:906:18)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickDomainCallback (internal/process/next_tick.js:218:9)
How to fix this issue?
This error not because of Probot, but the error is on GitHub ends.
This error is possibly because you have entered wrong User authorization call back URL, while creating a new GitHub application. Updating this will fix the issue.

How to use gspread with python-social-auth

I'm trying to use gspread with python-social-auth, I followed the sample describe on documentation and I've created this class to use as credential store:
class Credentials(object):
def __init__ (self, access_token=None, scope=None):
self.access_token = access_token
self.scope=scope
def refresh (self, http):
# get new access_token
# this only gets called if access_token is None
pass
And at my code I've used:
import gspread
credentials = Credentials(access_token=user.social_auth.get_access_token(),
scope=['https://spreadsheets.google.com/feeds'])
sh = gspread.authorize(credentials)
And asking any response from API using:
sh.get_spreadsheets_feed()
This error appears on the console:
*** RequestError: (401, '401: <HTML>\n<HEAD>\n<TITLE>Token invalid - AuthSub token has wrong scope</TITLE>\n</HEAD>\n<BODY BGCOLOR="#FFFFFF" TEXT="#000000">\n<H1>Token invalid - AuthSub token has wrong scope</H1>\n<H2>Error 401</H2>\n</BODY>\n</HTML>\n')
I have defined the scope at my settings and this is working well, for example trying to get contacts from Google Contacts
SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [
'https://www.googleapis.com/auth/contacts.readonly',
'https://www.googleapis.com/auth/spreadsheets.readonly'
]
Any ideas?
You have to add these scopes also to Python Social Auth settings:
SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [
...
'https://www.googleapis.com/auth/spreadsheets.readonly',
'https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive.file'
]

Google authentication

I got a problem on google authenticate, it worked for a month but since a few days I got this error :
Fatal error: Uncaught exception 'apiAuthException' with message
'Invalid token format' in /home/project/html/google/auth/apiOAuth2.php:127 Stack trace:
#0 /home/project/html/google/auth/apiOAuth2.php(89): apiOAuth2->setAccessToken('{? "access_tok...')
#1 /home/project/html/google/apiClient.php(132): apiOAuth2->authenticate(Array)
#2 /home/project/html/hk/connects/google.php(22): apiClient->authenticate()
#3 {main} thrown in /home/project/html/google/auth/apiOAuth2.php on line 127
In apiOAuth2.php I have the code :
$accessToken = json_decode($accessToken, true);
if (! isset($accessToken['access_token']) || ! isset($accessToken['expires_in']) || ! isset($accessToken['refresh_token'])) {
throw new apiAuthException("Invalid token format");
}
I noticed that google doesn't send me the $accessToken['refresh_token'].
It doesn't seem to come from google cause I did a correct connexion on http://stackoverflow.com
Maybe it's cause of my code :
session_start();
$client = new apiClient();
$plus = new apiPlusService($client);
if (!isset($_GET['code'])) {
header('Location: '.$client->createAuthUrl()); // Calls the same page
} else {
$client->authenticate(); // Fails at this level
}
EDIT:
I figured a way to do it, like I don't know what is refresh_token made for I added this line :
if (!isset($accessToken['refresh_token'])) $accessToken['refresh_token'] = 12345678910;
It works for the moment...
There is a new explicit parameter called "access_type" required by the google authentication api to obtain a valid refresh token.
With this parameter you declare that you need offline access to the account and the api provides you a refresh token.
Download the latest google PHP SDK that automatically handles the new required parameter