Wanting to build a microservice within Lambda.
I want it to be accessible via an HTTP request so I believe I need to configure it with API gateway. I am unsure if I should use API Gateway Proxy Request Event or API Gateway Proxy Response Event.
Also in terms of authenticating the user, what is the best way?
I am thinking using Auth0 so a user will essentially just send a JWT with the HTTP request.
Thanks
I use API Gateway Proxy Request. I configure the Integration Request to use Use Lambda Proxy integration which will result in Integration Response updating to Proxy integrations cannot be configured to transform responses.
I then handle responses within the lambda function itself. For example, I will have the following for a successful response:
context.succeed({
statusCode: 200,
headers: { 'Content-Type': 'Application/json'},
body
});
And for an example of an expected fail, I have:
context.succeed({
statusCode: 404,
headers: { 'Content-Type': 'Application/json'},
body: JSON.stringify({'Error': error})
});
NOTE: It is important to note I use context.succeed on error handling and not context.fail.
I developed my lambda locally in Node and used a combination of lambda-local and lambda-tester for debugging/testing functionality. For example, I would run the following command to pass in the lambda and the event:
lambda-local -f ~/Desktop/lambdaNode/myNewAPI.js -e ~/Desktop/lambdaEvents/testEvent.json
An example event will look like this:
{
"queryStringParameters":
{
"param1": "1234567890",
"param2": "0987654321",
}
}
For my unit tests, I used lambda-tester along with mocha as follows:
const LambdaTester = require( 'lambda-tester' );
describe('handle my new lambda: ', () => {
it('should do exactly what I expect', () => {
return LambdaTester( myNewAPI.handler )
.event( testEvents.newLambdaEvent )
.expectSucceed( ( result ) => {
expect( result.statusCode ).to.equal(200);
});
});
});
Test the above with npm test if you're setup for that, otherwise just mocha testFile
For my use case, authentication is handled differently as it is an internal API. For your case, I think JWT is the best way forward there, although I am sorry I cannot provide more info in that regard.
Related
I configured and initialized AWS Amplify for my ReactNative/Expo app and added a REST Api. Im new to AWS in general, but im assuming that once I add the API, my project is populated with amplify/backend folders and files and is ready for consumption.
So i tried to create a simple post request to create an item in my DynamoDB table with
import { Amplify, API } from "aws-amplify";
import awsconfig from "./src/aws-exports";
Amplify.configure(awsconfig);
const enterData = async () => {
API.post("API", "/", {
body: {
dateID: "testing",
},
headers: {
Authorization: `Bearer ${(await Auth.currentSession())
.getIdToken()
.getJwtToken()}`
}
})
.then((result) => {
// console.log(JSON.parse(result));
})
.catch((err) => {
console.log(err);
});
};
const signIn = async () => {
Auth.signIn('test#test.com', 'testpassword')
.then((data) => {
console.log(data)
enterData() //enterData is attempted after signin is confirmed.
})
.catch((err) => {
console.log(err)
})
}
signIn()
I did not touch anything else in my project folder besides including the above in my App.tsx because im unsure if i need to and where. I got a 403 error code and it "points" to the axios package but im not sure if issue is related to aws integration.
I configured the REST Api with restricted access where Authenticated users are allowed to CRUD, and guests are allowed to Read. How could I even check if I am considered an "Authorized User" .
Yes, AWS Amplify API category uses Axios under the hood so axios is related to your problem.
Probably you get 403 because you didn't authorized, for Rest API's you need to set authorization headers,
I don't know how is your config but you can take help from this page. Please review the "Define Authorization Rules" section under the API(REST) section.
https://docs.amplify.aws/lib/restapi/authz/q/platform/js/#customizing-http-request-headers
To check authorization methods, you can use "Auth" class like that also you can see auth class usage in the above link.
import { Amplify, API, Auth } from "aws-amplify";
https://aws-amplify.github.io/amplify-js/api/classes/authclass.html
I'm trying to call an AWS hosted API from my VueJS app, which is running on my localhost:8080. I have used this blog post to setup the vue.config.js with this block:
module.exports = {
devServer: {
proxy: 'https://0123456789.execute-api.eu-west-1.amazonaws.com/'
},
...
}
With this in place, I can use this code to make a GET request to an endpoint at that host:
this.$axios
.get('https://0123456789.execute-api.eu-west-1.amazonaws.com/mock/api/endpoint',
{
headers: {
'Content-Type': 'application/json'
}})
This is because I have configured the AWS API Gateway mock endpoint to return these headers for the OPTIONS method:
Access-Control-Allow-Headers: 'Cache-Control,Expires,Pragma,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'
Access-Control-Allow-Methods: 'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT'
Access-Control-Allow-Origin: '*'
However, I cannot make this call:
this.$axios
.get('https://0123456789.execute-api.eu-west-1.amazonaws.com/lambda/api/function',
{
headers: {
'Content-Type': 'application/json'
}})
This endpoint is a Lambda integration and also has an OPTIONS method with the same headers as above.
Why should both endpoints, configured the same way, have different responses for axios?
UPDATE
As advised by #deniz, I have updated the .env.development file to contain:
VUE_APP_API_URI=https://0123456789.execute-api.eu-west-1.amazonaws.com/
I have also updated the axios requests to:
let url = 'mock/api/endpoint'
let headers = {
headers: {
'Content-Type': 'application/json',
},
}
this.$axios
.get(url, headers)
...and...
let url = 'lambda/api/function'
let headers = {
headers: {
'Content-Type': 'application/json',
},
}
this.$axios
.get(url, headers)
The result I get for the first GET request is:
200 OK
However the second request's response is:
Access to XMLHttpRequest at 'https://0123456789.execute-api.eu-west-1.amazonaws.com/lambda/api/function' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Your config for your dev env. as a proxy setup is doing nothing else then pretend to be someone else.
Thats why you dont get any CORS issues when you work with a proxy. its a kinda bottleneck which acts like "i am someone else, not localhost"
module.exports = {
devServer: {
proxy: 'https://0123456789.execute-api.eu-west-1.amazonaws.com/'
},
...
}
from now on all your requests came from this very proxy based URL
https://0123456789.execute-api.eu-west-1.amazonaws.com/
if you try to access the api like this:
this.$axios
.get('https://0123456789.execute-api.eu-west-1.amazonaws.com/lambda/api/function',
{
headers: {
'Content-Type': 'application/json'
}})
you should keep in mind that you are already pretend that your proxy is doing his desguise stuff and still acts like its from a other source.
your URL when you call the API looks like this now, if i am not completely wrong:
https://0123456789.execute-api.eu-west-1.amazonaws.com/https://0123456789.execute-api.eu-west-1.amazonaws.com/lambda/api/function
all you have to do is change the axios url in your request to:
this.$axios
.get('lambda/api/function',
{
headers: {
'Content-Type': 'application/json'
}})
and try again.
UPDATE
VUE_APP_API_URI=https://0123456789.execute-api.eu-west-1.amazonaws.com/
wrap your URL string into quotes, like this and remove the last slash.
VUE_APP_API_URI='https://0123456789.execute-api.eu-west-1.amazonaws.com'
thats a common practice to handle .env vars.
2.
the CORS error you get is a result of not using proxy anymore.
your requesting data from a other source now and this is no allowed on modern browsers like FireFox or Chrome etc.
here you have to handle the server side configs in your API:
https://0123456789.execute-api.eu-west-1.amazonaws.com
because if you go like that you need to give your localhost and your backend the permission to handle requests if the requests are made from different sources, like in your case:
i am localhost and i request data from https://0123456789.execute-api.eu-west-1.amazonaws.com
normally this is forbidden and is a highly risk on security
But the solution is...
As you did before in your AWS API
Access-Control-Allow-Origin: '*' is the important part which handles your "CORS" issues.
make sure it is setup correct and works as intended. maybe play around with that and set localhost instead of * (allow for all)
3.
i highly recommend you to use the proxy way on development and use the non proxy way only for production, and just allow CORS for your frontend only.
I have a Lambda function integrated with API Gateway and the stack was deployed as cloud formation template. When I try to test the endpoint in the AWS web console I got correct response but when I try to invoke the deployed version of the API I got that error.
"message": "Could not parse request body into json: Unrecognized token ....etc"
I tried this mapping { "body" : $input.json('$') } in the integration request, but didn't work.
Here is the JSON I am trying to send using POSTMAN
{
"description": "test description",
"status": "test status"
}
and the request has header: Content-Type: application/json
Here you are screenshots for POSTMAN request body & headers, and the response from the API:
Any Solution guys?
UPDATE:
I put a mapping template at integration request level as the following:
{
"body-json" : $input.json('$')
}
And updated the lambda function to log the coming request, then made 2 requests:
First one: from API Gateway test web console:
I found the following in the cloudwatch logs:
INFO {
body: {
description: 'test',
projectId: 23,
action: 'test',
entity: 'test',
startDate: '01-01-2020',
endDate: '01-01-2020'
}
}
Second one: from POSTMAN:
I found the following in the cloudwatch logs:
INFO {
body: 'ewogICAgImRlc2NyaXB0aW9uIjogInRlc3QiLAogICAgInByb2plY3RJZCI6IDIzLAogICAgImFjdGlvbiI6ICJ0ZXN0IiwKICAgICJlbnRpdHkiOiAidGVzdCIsCiAgICAic3RhcnREYXRlIjogIjAxLTAxLTIwMjAiLAogICAgImVuZERhdGUiOiAiMDEtMDEtMjAyMCIKfQ=='
}
That indicates that in case of making the request using POSTMAN, the JSON payload is stringified automatically. What can cause such thing? and how to deal with it?
In this case we need to edit the mapping template since we are not using a proxy integration.
"body-json" : $input.json('$')
//also if binary data type is enabled for your api your body will be a base64
//encoded string which could be decoded using
$util.base64Decode($input.json('$'))
Also binary data types maybe enabled by default, search for these in the SAM template
x-amazon-apigateway-binary-media-types:
- '*/*'
You need to add a custom header in your response for it to respond correctly.
// The output from a Lambda proxy integration must be
// in the following JSON object. The 'headers' property
// is for custom response headers in addition to standard
// ones. The 'body' property must be a JSON string. For
// base64-encoded payload, you must also set the 'isBase64Encoded'
// property to 'true'.
let response = {
statusCode: responseCode,
headers: {
"x-custom-header" : "my custom header value"
},
body: JSON.stringify(responseBody)
};
I am using AWS Cognito for Authentication using user pools and I have all my APIs configured on the API gateway. I directly hit cognito from the Angular client, store the tokens returned by Cognito in local storage and use them in subsequent calls.
The problem however is, if the token I send from Angular has expired the Cognito authentication fails and no Integration backend is hit in this case. As a result, I am getting a 401 error in Chrome.
The interesting thing however is that this 401 code is not available to me in the HTTP response object that is passed to Angular. A default 0 code is received by the Angular and this seems to be the case with all the error code received from server (either cognito or backend).
I tried to explore around and found that the issue might be because the gateway is not sending proper CORS headers in the error cases. I have read following related docs but unfortunately I couldn't find out a way to resolve the issue.
Can someone suggest a solution to this.
Edit: I also read somewhere that it is a known AWS issue. Is that the case ?
You can manage the Cognito session before making the call to the API Gateway.
In the example below, the getSession method has a callback that prints out any error messages to the console, and returns.
////// Cognito.js
import {
CognitoUserPool,
CookieStorage
} from 'amazon-cognito-identity-js'
import config from '../config'
const cookieSettings = {
domain: '.xxxxxxxxxxx.com',
secure: true
}
export default {
cookieSettings,
pool: new CognitoUserPool({
UserPoolId: config.UserPoolId,
ClientId: config.ClientId,
Storage: new CookieStorage(cookieSettings)
})
}
//////
////// actions.js
import Cognito from './Cognito'
export function fetchUser() {
// get cognito user cookies
const cognitoUser = Cognito.pool.getCurrentUser()
if (cognitoUser != null) {
// try to get session from cognito
cognitoUser.getSession(function(err, session) {
if (err) {
console.log(err)
return;
}
fetch('https://api-gateway-url', {
headers: {
Authorization: 'Bearer ' + session.getAccessToken().getJwtToken(),
}
})
.then(response => response.json())
.then(json => console.log(json))
})
}
}
I'm trying to convert a working Lumen API service to AWS, and am stumped on getting an external REST API service to work. The service returns data compressed, but this fact isn't being passed through back to the app (Vue) in the browser properly. I tried adding in the headers in the response, as shown below, but it still isn't working. I can see the headers in the response in the browser console, but the browser still isn't interpreting it, so the data still looks like garbage. Any clues as to how to make this work?
var req = require('request');
exports.handler = function (event, context, callback) {
const params = {
url: 'http://api.service',
headers: { 'Authorization': 'code',
'Accept-Encoding': 'gzip,deflate',
'Content-Type': 'application/json' },
json: {'criteria': {
'checkInDate': '2019-10-22',
'checkOutDate': '2019-10-25',
'additional': {'minimumStarRating': 0},
'cityId': 11774}}
};
req.post(params, function(err, res, body) {
if(err){
callback(err, null);
} else{
callback(null, {
"statusCode": 200,
"headers": {
"Content-Type": "application/json",
"Content-Encoding": "gzip"
},
"body": body
});
}
});
};
In the case you are seeing all scrambled characters, chance is you have not let API Gateway treat your Lambda answer as binary yet ( Since it is gzip-ed from your lambda )
Take a look at the document
https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings-configure-with-console.html
And this article
Unfortunately, the API Gateway is currently oblivious of gzip. If
we’re using a HTTP proxy, and the other HTTP endpoint returns a
gzipped response, it’ll try to reencode it, garbling the response.
We’ll have to tell the API Gateway to treat our responses as binary
files — not touching it in any way.
https://techblog.commercetools.com/gzip-on-aws-lambda-and-api-gateway-5170bb02b543