How to get the req headers in lambda - node.js

I have try to send some data to AWS lambda and add data to database.I know how to get the header if using a local server but I don't know where and how to get the header using AWS. I have tried to find some possible solution but I still dont understand and solve my problem.
My api is something like that:
export const delectData = function (accessToken, id) {
return apiClient.post('end point get from API GATEWAY',
{ tableName: '***',
id: id },
{
headers: {
Authorization: `Bearer ${accessToken}`
}
})
I am using dynamodb to store my data. And I need to get the headers which is the accesstoken for doing validation. Can someone explain to me how to get the header or how to setup in APIGATE step by step? Since the doc in AWS is very unclear for me...
UPDATE: in my postman, It is :

Assuming your API is not a Lambda Proxy integration
1.Go to your method Integration Request
2.Click on Mapping Templates
3.Choose When no template matches the request Content-Type header
3.Click on application/json under Content-Type -> if does not exist create one.
4.Scroll down and put this template:
{
"YourHeader" : "$input.params('YourHeader')",
"body" : $input.json('$')
}
5.Redeploy your API.
6.In your Lambda event.YourHeader

Related

SendGrid API v3 using NodeJS #sendgrid/client - Call is Unauthorized / API Key is valid with full permissions

I'm really struggling with a problem where every call I make to the #sendgrid/client comes back unauthorized. The exact same key can be used with #sendgrid/mail in the same code and it works fine.
I've tried everything but cannot get the NodeJS #sendgrid/client to work. I've even tried a brand new API Key and still get unauthorized.
I'm trying to use the /suppressions API. I can make the exact same call, with the same API key, in Postman and it works fine.
What am I doing wrong here?
Here is my code:
sgApiKey = config.get('sendGrid_APIKey');
sgClient.setApiKey(sgApiKey);
const email = "test#abc.com";
const headers = {
"on-behalf-of": "The subuser's username. This header generates the API call as if the subuser account was making the call."
};
const request = {
url: `/v3/asm/suppressions/global/${email}`,
method: 'GET',
headers: headers
}
sgClient.request(request)
.then(([response, body]) => {
console.log(response.statusCode);
console.log(response.body);
})
.catch(error => {
console.error(error);
});
I have tried creating a new API key with full permissions and it still does not work.
I'm expecting that my existing API key I already use for emailing should work to all the /suppression API.

I am facing issue while reading request body in Azure function node js

In my azure function post call i am passing body like this
{
"license":{
"licensepolicy": "NA",
"metadata":{
"tenantname":"tenantname",
},
"licensetype":"type"
},
"customer":{
"name":"TEst User",
"emailaddress":"email",
"company":"test"
}
}
In my code I am accessing this request body like below
context.log(req.body.license);
Its giving undefined log, I don't know why but its working in normal node js code but in azure function its not working.
Please assist me if I am wrong somewhere
thanks in advance
Make sure to check your post method whether it contains the Header 'Content-Type': 'application/json'
headers: {
'Content-Type': 'application/json'
}
If you are not sending the Json response you have to convert that into Json object in your code to retrieve that information.
# convert request into Json object and access those informations.
const parsedData = JSON.parse(req)
context.log(parsedData.body.license);

Cannot get the headers after I set the mapping template in API GATEWAY

I would like to call an api with a header and body for admin user delete a user data like this:
apiClient.post('***endpoint***',
{ tableName: '***',
id: id },
{
headers: {
Authorization: accessToken
}
})
and I want to show the detail in lambda first before I write any function to access my db:
var AWS = require('aws-sdk')
AWS.config.update({ region: '***' })
var ddb = new AWS.DynamoDB()
exports.handler = async function (event , ctx , callback) {
return event
};
and in APIGATEWAY, I set the following
{
"Authorization" : "$input.params('Authorization'),
"body" : $input.json('$')
}
with content-type isapplication/json in Integration Request
Then when I test the api in Method Test .
In Header , I type "testaccesstoken",
In body , I type { "id":"1", "tableName":"test"},
But the result is{
"Authorization": "",
"body": {
"id": "1",
"tableName": "test"
}
}
Can anyone explain to me why I still cannot get the header?
Also when I test in poseman,I try like this:,
and I get an error
I hv already deployed the API but why I cannot test in postman??
In your Postman, set your header is Authorization instead of "Authorization"
I noticed you mentioned the mapping template and passthrough behavior but nothing about mapping it in your Method Request or the header field in Integration Request in API Gateway. There is a recent answer here I think may give you some things to verify are set correctly, as I suspect that may be the issue.
It also covers using a proxy integration instead, let me know if there is a more specific issue in the comments and I'll adjust my answer if needed!

getting 403 error while sending file to githib via REST using nodejs

I want to send multiple files to Github repository via nodejs. Tried several approaches and end up using node-rest-client module. Tried below code send a sample file to repository called 'metadata'. But after post I am getting error message "Request forbidden by administrative rules. Please make sure your request has a User-Agent header"...please let me know if anyone faced this error before and get rid of it.
convertval = "somedata";
var dataObj = {
"message": "my commit message",
"committer": {
"name": "Scott Chacon",
"email": "ravindra.devagiri#gmail.com"
},
"content": "bXkgbmV3IGZpbGUgY29udGVudHM="
}
debugger;
var Client = require('node-rest-client').Client;
var client = new Client()
var args = {
data: dataObj,
headers: { 'Content-Type': 'application/json' },
};
client.post("https://api.github.com/repos/metadata/contents", args, function (data, response) {
console.log("file send: True : " + data);
});
According to the REST API:
All API requests MUST include a valid User-Agent header. Requests with
no User-Agent header will be rejected.
First of all, you need to define 'User-Agent' with value 'request' in your request header. Refer to this link.
Second, endpoint you are trying to call might require authentication. Generate a personal token from here, add that token in your request header, 'Authorization': 'token '.
If you're using Git extensively in your code, I suggest you to use this - Nodegit.
Edit:
I don't think sending multiple files in a single request is possible in 'Contents' endpoints group (link).
You can checkout Git Data API (as discussed here).

How to call Management API v2 to send verification mail from within a rule?

I'm writing a rule in Auth0 to trigger a verification email if a certain condition is met. To make the example small I have included the code which I am using to send the verification mail (I have removed out the unwanted code).
var url = 'https://myname.au.auth0.com/api/v2/jobs/verification-email';
var token = 'Bearer {{token}}'; //This is where the problem is how do I get the token
var userId = user.user_id;
request.post({
url: url,
headers: {
Authorization: 'Bearer {{token}}',
},
json: {
"user_id": user.user_ID
},
timeout: 5000
},
function(err, res, body) {
console.log(err);
console.log(res);
});
In the body I get the following error
{ statusCode: 400,
error: 'Bad Request',
message: 'Bad HTTP authentication header format',
errorCode: 'Bearer' }
I guess I need to pass in the access token or something like that in the header. How do I get this done?
I also saw the following article (https://auth0.com/docs/email/custom), however I'm not sure what secretToken is?
Starting from the bottom, the article (https://auth0.com/docs/email/custom) is aimed at users that want additional flexibility and use their own custom email handling. The secretToken on that example it's just to illustrate a possible - and very simple - way that their own custom email API could validate that they were being called from Auth0; in conclusion it would work almost as an API key.
If you only need to trigger a verification email through the system provided by Auth0 you're using the correct approach (Management API v2). You have more than one way to obtain a token that allows you to call this API:
Using the client credentials grant
Using the Auth0 Management API v2 Explorer
The second option would be the easiest to get started, but do take in consideration that there's a deprecation notice for that one.
Once you obtain the token, you also need to correctly pass it to the API. The code you showed may be only sample code, but make sure that you don't end up including the Bearer scheme twice, more specifically var token = 'Bearer {{token}}'; should instead just be var token = '{{token}}'; and then you would use the token variable when creating the HTTP header.
Just created the below empty rule that will get called when user tries to login and email is not yet verified and it works like a charm :D
function (user, context, callback) {
if (!user.email_verified) {
console.log("User is: " + user.user_id);
var ManagementClient = require('auth0#2.6.0').ManagementClient;
var management = new ManagementClient({
token: auth0.accessToken,
domain: auth0.domain
});
var new_userobj = {user_id:user.user_id};
management.sendEmailVerification(new_userobj,callback(new UnauthorizedError('Please click on the link in the email we have sent you to continue to login.')));
} else {
return callback(null, user, context);
}
}
I received the same error when using the wrong token, though for a different api call. I recreated your issue by using a user's access_token obtained by calling {{api-audience}}users/{{user_id}}. That token should look something like this: A1bCd2efg34IJkl5
Try using a client's access_token obtained by making this call:
curl --request POST \
--url https://{{domain}}/oauth/token \
--header 'content-type: application/json' \
--data '{
"client_id":"{{client_id}}",
"client_secret":"{{client_secret}}",
"audience":"{{audience}}",
"grant_type":"client_credentials"
}'
That token will be a full JWT.

Resources