How to access custom header from AWS Lambda Authorizer? - aws-api-gateway

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.

Related

Unable to get resonse from import contacts sendgrid API using python

Below is the call I am trying to make -
I used field mapping in below data -
data = {
"file_type": "csv",
"field_mappings": [
"_rf2_T",
"_rf0_T",
"_rf1_T",
"_rf10_T",
"w1_T",
"w45_T",
"w46_T",
"w44_T",
"w2_D",
"w43_T"
]
}
print("--data---",data)
response = sg.client.marketing.contacts.put(
request_body=data
)
#print("--data---",data)
print(response.status_code)
print(response.body)
print(response.headers)
and getting below error
{'errors': [{'field': 'contacts', 'message': 'at least one contact is required'}]}
I am expecting upload url and header from api call

RESTful client in Unity - validation error

I have a RESTful server created with ASP.Net and am trying to connect to it with the use of a RESTful client from Unity. GET works perfectly, however I am getting a validation error when sending a POST request. At the same time both GET and POST work when sending requests from Postman.
My Server:
[HttpPost]
public IActionResult Create(User user){
Console.WriteLine("***POST***");
Console.WriteLine(user.Id+", "+user.sex+", "+user.age);
if(!ModelState.IsValid)
return BadRequest(ModelState);
_context.Users.Add(user);
_context.SaveChanges();
return CreatedAtRoute("GetUser", new { id = user.Id }, user);
}
My client:
IEnumerator PostRequest(string uri, User user){
string u = JsonUtility.ToJson(user);
Debug.Log(u);
using (UnityWebRequest webRequest = UnityWebRequest.Post(uri, u)){
webRequest.SetRequestHeader("Content-Type","application/json");
yield return webRequest.SendWebRequest();
string[] pages = uri.Split('/');
int page = pages.Length - 1;
if (webRequest.isNetworkError || webRequest.isHttpError){
Debug.Log(pages[page] + ":\nReceived: " + webRequest.downloadHandler.text);
}
else{
Debug.Log(pages[page] + ":\nReceived: " + webRequest.downloadHandler.text);
}
}
}
I was trying both with the Json conversion and writing the string on my own, also with the WWWForm, but the error stays.
The error says that it's an unknown HTTP error. When printing the returned text it says:
"One or more validation errors occurred.","status":400,"traceId":"|b95d39b7-4b773429a8f72b3c.","errors":{"$":["'%' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0."]}}
On the server side it recognizes the correct method and controller, however, it doesn't even get to the first line of the method (Console.WriteLine). Then it says: "Executing ObjectResult, writing value of type 'Microsoft.AspNetCore.Mvc.ValidationProblemDetails'".
Here're all of the server side messages:
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 POST http://localhost:5001/user application/json 53
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0]
Executing endpoint 'TheNewestDbConnect.Controllers.UserController.Create (TheNewestDbConnect)'
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[3]
Route matched with {action = "Create", controller = "User"}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IActionResult Create(TheNewestDbConnect.Data.Entities.User) on controller TheNewestDbConnect.Controllers.UserController (TheNewestDbConnect).
info: Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor[1]
Executing ObjectResult, writing value of type 'Microsoft.AspNetCore.Mvc.ValidationProblemDetails'.
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2]
Executed action TheNewestDbConnect.Controllers.UserController.Create (TheNewestDbConnect) in 6.680400000000001ms
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
Executed endpoint 'TheNewestDbConnect.Controllers.UserController.Create (TheNewestDbConnect)'
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished in 11.3971ms 400 application/problem+json; charset=utf-8
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
I have no idea what is happening and how to solve it. Any help will be strongly appreciated!
Turned out I was just missing an upload handler. Adding this line solved it: webRequest.uploadHandler = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(JsonObject));

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

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

Authenticate from Retrofit with JWT token to Rest server

my server is Flask based, my client is android studio, and i'm communication using retrofit.
The problem is that i'm not able to pass the jwt token correctly from the android to the server after logging in.
With postman it's working good:
{{url}}/auth - I'm logging in as the user, and getting the JWT token.
Later i'm adding "Authorization" header, with the Value "JWT {{jwt_token}}" and
{{url}}/users/john - I'm asking for user info, which is recieved without problems.
The endpoint from android studio:
public interface RunnerUserEndPoints {
// #Headers("Authorization")
#GET("/users/{user}")
Call<RunnerUser> getUser(#Header("Authorization") String authHeader, #Path("user") String user);
The call itself (The access_token is correct before sending!):
final RunnerUserEndPoints apiService = APIClient.getClient().create(RunnerUserEndPoints.class);
Log.i("ACCESS","Going to send get request with access token: " + access_token);
Call<RunnerUser> call = apiService.getUser("JWT" + access_token, username);
Log.i("DEBUG","Got call at loadData");
call.enqueue(new Callback<RunnerUser>() {
#Override
public void onResponse(Call<RunnerUser> call, Response<RunnerUser> response) { ....
The response error log from the server:
File "C:\Users\Yonatan Bitton\RestfulEnv\lib\site-packages\flask_restful\__init__.py", line 595, in dispatch_request
resp = meth(*args, **kwargs)
File "C:\Users\Yonatan Bitton\RestfulEnv\lib\site-packages\flask_jwt\__init__.py", line 176, in decorator
_jwt_required(realm or current_app.config['JWT_DEFAULT_REALM'])
File "C:\Users\Yonatan Bitton\RestfulEnv\lib\site-packages\flask_jwt\__init__.py", line 151, in _jwt_required
token = _jwt.request_callback()
File "C:\Users\Yonatan Bitton\RestfulEnv\lib\site-packages\flask_jwt\__init__.py", line 104, in _default_request_handler
raise JWTError('Invalid JWT header', 'Unsupported authorization type')
flask_jwt.JWTError: Invalid JWT header. Unsupported authorization type
10.0.0.6 - - [30/Sep/2017 01:46:11] "GET /users/john HTTP/1.1" 500 -
My api-client
public class APIClient {
public static final String BASE_URL = "http://10.0.0.2:8000";
private static Retrofit retrofit = null;
public static Retrofit getClient(){
if (retrofit==null){
retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
Log.i("DEBUG APIClient","CREATED CLIENT");
return retrofit;
}
}
Actually i'm really stuck. Tried to follow along all of the tutorials at retrofit's website without success.
I'm sure that there is a simple solution, I just need to add "Authorization" Header with Value "JWT " + access_token like it works in postman and that's it! Thanks.
EDIT:
The problem was the build of the access_token in my client.
I did:
JsonElement ans = response.body().get("access_token");
access_token = "JWT " + ans.toString();
Which I should have done:
JsonElement ans = response.body().get("access_token");
access_token = "JWT " + ans.getAsString();
So before it sent "JWT "ey..." " (Double "" )
And now it sends "JWT ey ... "
Let's start to look at what we know about the problem.
We know that the request is sent
We know that the server processes the request
We know that the JWT is invalid thanks to the error:
JWTError('Invalid JWT header', 'Unsupported authorization type')
If we look for that error in the flask_jwt source code, we can see that this is where our error is raised:
def _default_request_handler():
auth_header_value = request.headers.get('Authorization', None)
auth_header_prefix = current_app.config['JWT_AUTH_HEADER_PREFIX']
if not auth_header_value:
return
parts = auth_header_value.split()
if parts[0].lower() != auth_header_prefix.lower():
raise JWTError('Invalid JWT header', 'Unsupported authorization type')
elif len(parts) == 1:
raise JWTError('Invalid JWT header', 'Token missing')
elif len(parts) > 2:
raise JWTError('Invalid JWT header', 'Token contains spaces')
return parts[1]
Basically flask_jwt takes the Authorization header value and tries to split it into two. The function split can split a string by a delimiter, but if you call it without a delimiter it will use whitespace.
That tells us that flask_jwt expects a string that contains 2 parts separated by whitespace, such as space, and that the first part must match the prefix we are using (in this case JWT).
If we go back and look at your client code, we can see that when you are building the value to be put in the Authorization header you are not adding a space between JWT and the actual token:
apiService.getUser("JWT" + access_token, username);
This is what you should have been doing:
apiService.getUser("JWT " + access_token, username);
Notice the space after JWT?

Backend Error (HttpError 500) on Google Search Console API calls (webmasters/v3)

I prepared code that should fetch data from google webmaster console new Web API (v3).
import os
from oauth2client.service_account import ServiceAccountCredentials
import httplib2
from apiclient.discovery import build
import googleapiclient
import json
client_email = '<ACCOUNT_IDENTIFIER>#<PROJECT_IDENTIFIER>.iam.gserviceaccount.com'
scopes = ['https://www.googleapis.com/auth/webmasters.readonly',
'https://www.googleapis.com/auth/webmasters']
private_key_path = os.getcwd() + os.path.normpath('/key.p12')
http = httplib2.Http()
credentials = ServiceAccountCredentials.from_p12_keyfile(client_email,
private_key_path,
private_key_password="notasecret",
scopes=scopes
)
http_auth = credentials.authorize(http)
webmasters_service = build('webmasters', 'v3', credentials=credentials, http=http_auth)
query_params = {"startDate": "2016-03-01", "endDate": "2016-03-02"}
try:
quered_results = webmasters_service.searchanalytics().query(
key="<KEY>",
siteUrl="http://<SITE_DOMAIN>/",
body=json.dumps(query_params),
fields="rows",
alt="json"
).execute()
print(quered_results)
except googleapiclient.errors.HttpError as e:
print(e)
Execution results with error:
<HttpError 500 when requesting https://www.googleapis.com/webmasters/v3/sites/http%3A%2F%2F<SITE_DOMAIN>%2F/searchAnalytics/query?key=<KEY>&alt=json&fields=rows returned "Backend Error"
The code from above is for authorization with ssh key with p12 format. Key file is correct. Using client_secrets.json end up with the same error, code. The json for error is:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "backendError",
"message": "Backend Error",
}
],
"code": 500,
"message": "Backend Error"
}
}
I did connect email to webmaster tools console.
Authorization seems to work since there is no errors for used key/account
Any ideas?
I've noticed that the same error occures when I fetch on https://developers.google.com/apis-explorer with "Request body" improperly set, but I do not see error in JSON I send. BTW It would be nice to have some validation message about that...
Found it! body parameter should actually by python object, not JSON formatted string!
body=json.dumps(query_params),
Should be
body=query_params,