My First Post      My Facebook Profile      My MeOnShow Profile      W3LC Facebook Page      Learners Consortium Group      Job Portal      Shopping @Yeyhi.com

Pages










Showing posts with label aws. Show all posts
Showing posts with label aws. Show all posts

Friday, August 16, 2024

Enable CORS on a resource using the AWS API Gateway console

 Sometimes while hitting an API gateway you get error suggesting No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.


In such a case, sometimes people suggest to set the request mode to 'no-cors' like so:

fetch(url, {

    mode: "no-cors",

    ...

})

But if you're getting CORS issues this is not the solution. If the API endpoint is something that you control, then you have to fix those CORS issue there. If the API endpoint is not something that you control, then you have to proxy your request through a server that does have CORS enabled.

You need to remove the mode: 'no-cors' setting from your request. Setting no-cors mode is exactly the cause of the problem you’re having. A no-cors request makes the response type opaque. The log snippet in the question shows that. Opaque means your frontend JavaScript code can’t see the response body or headers.

With no-cors — JavaScript may not access any properties of the resulting Response

So the effect of setting no-cors mode is essentially to tell browsers, “Don’t let frontend JavaScript code access the response body or headers under any circumstances.”

People sometimes try setting no-cors mode when a response doesn’t include the Access-Control-Allow-Origin response header or else because the request is one that triggers a CORS preflight, and so your browser does an OPTIONS preflight. But using no-cors mode isn’t a solution to those problems. The solution is either to:

  1. configure the server to which you’re making the request such that it sends the Access-Control-Allow-Origin response header, and such that it handles OPTIONS requests
  2. or set up a CORS proxy using code from https://github.com/Rob--W/cors-anywhere/ or such; see the How to use a CORS proxy to get around “No Access-Control-Allow-Origin header” problems section of the answer at No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API 
  3. Temporarily you can also use Chrome extension of Enabling CORS. But it is for debugging phase only.

However, it is evident that sometimes you clearly need to Enable CORS on a resource. You can do this using the API Gateway console.


To enable CORS support on a REST API resource
  1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway

  2. Choose an API.

  3. Choose a resource under Resources.

  4. In the Resource details section, choose Enable CORS.



Next Steps/settings In the Enable CORS box:
  • (Optional) If you created a custom gateway response and want to enable CORS support for a response, select a gateway response.
  • Select each method to enable CORS support. The OPTION method must have CORS enabled.
  • If you enable CORS support for an ANY method, CORS is enabled for all methods.
  • In the Access-Control-Allow-Headers input field, enter a static string of a comma-separated list of headers that the client must submit in the actual request of the resource. Use the console-provided header list of 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token' or specify your own headers.
  • Use the console-provided value of '*' as the Access-Control-Allow-Origin header value to allow access requests from all origins, or specify origins to be permitted to access the resource.
  • Choose Save.



After this, deploy the API again and see the fun in next call!


Tuesday, June 30, 2020

aws_key_gen login for getting AWS Keys locally on command line

If you or your team is working with AWS, you might know how important it is to get the keys while dev or debugging the code.


Command is:
$ ~/ECPCP/aws_key_gen login



It will then promt you to enter your login credentials into corporate account:
Enter your password for MAJFTECH\mfaiz:

Duo two-factor login for MAJFTECH\mfaiz



Then it will ask you to select the method for verification:

For eg. Enter a passcode or select from one of the following options:

1. Duo Push to Android (+XX XXXXX X8847)
2. Phone Call to Android (+XX XXXXX X8847)
3. Duo Push to Android (+XX XXXXX X7658)
4. Phone Call to Android (+XX XXXXX X7658)

Passcode or option (1-4): 4
Dialing +XX XXXXX X7658...
Answered. Press any key on your phone to log in.
Success. Logging you in...



Then it will ask you to choose one of the many AWS accounts that your organization might be using:

Eg. Available AWS Accounts
  [ 1] majf-product--integration-test (12344567)
  [ 2] w3lc-test (123444567)
  [ 3] w3lc-techp-test (162344567)
  [ 4] majftech-lab (982344567)

Please choose an AWS Account: 3



Then it asks you to chosse the role :
Available AWS IAM Roles in w3lc-techp-test (162344567)
  [ 1] ReadOnly (arn:aws:iam:: 162344567:role/ReadOnly)
  [ 2] User (arn:aws:iam:: 162344567:role/User)
Please choose an AWS IAM Role: 2



Finally you get the keys as follows:
Generated new temporary access keys
Role:        arn:aws:iam::132343860784:role/User
Expiration:  Tue Jun 30 08:24:55 UTC 2020 (1 hour from now)


Cheers :)

Thursday, January 30, 2020

Mapping template, Velocity Language & JsonPath: Guide to Api Gateway mapping templates mechanism

Amazon’s API Gateway provides the facilities to map an incoming request’s payload to match the required format of an integration backend. It uses the concept of “models” and “mapping templates” to specify the mapping between the client payload and the server payload.

The API Gateway mapping templates are used to transform an incoming payload into a different format. API Gateway allows you to define input mapping templates, for mapping the incoming request from a client to a server format, and output mapping templates, for mapping the outgoing response from the server to a client format.

Let us all remember that the mappings are defined using the Velocity Template Language combined with JSONPath expressions.

Velocity is a Java-based templating engine that uses a template language to reference objects in Java code. Velocity can be used to generate web XML, HTML or SQL from templates, for example. Here, we will use it to define the mapping between an input and output model.
A Velocity Template Language (VTL) template is composed of statements which begin with the # character and a followed by a directive. Also, it has references, which begin with the $ character. More generally, references begin with $ and are used to get or set something. Directives begin with # and are used to do something.
We can use the statement above to define an HTML template that sets a reference to a value, and retrieves that reference.

  
  #set( $foo = "Velocity" )
  Hello $foo World!
  
For more on VTL, consult the user guide.

In API Gateway mapping templates, the input to your Velocity template is defined by the reference variable $input. To access particular portions of the input JSON document within the template, use JSONPath.
JSONPath provides an XPath-like method of referring to a JSON structure. IN JSONPath, the abstract name $ refers to the root-level object. From this root-level object, you can use dot-notation to select more restrictive portions of the document. 
For example, to reference the playerId of the player model, you would use the following JSONPath expression.
$.playerId
or, you can use a bracket-notation to perform the same selection.
#['playerId']
More complex selections can be done using * for a wildcard, @ to refer to the current node in the document, array indexing, or recursive descent.

Now, we can put together a mapping template for our Player model. This template will just copy the input to the output with new names for field properties. In particular, it will convert an input document of
{
    "id": "AJamal",
    "alias": "Aha Jamal",
    "displayName": "Anwar Jamal Faiz",
    "profilePhotoUrl": "https://api.example.com/player/AJamal/avatar.png"
}
to an output document of
{
    "id": "AJamal",    "alias": "Aha Jamal",    "name": "Anwar Jamal Faiz",    "photo": "https://api.example.com/player/AJamal/avatar.png"}
The mapping to perform the above transformation is specified below, with some inline VTL comments added.
## Set the variable inputRoot to the root JSON document
#set($inputRoot = $input.path('$')) {

    ## Assign output properties to input properties
    "id": "$inputRoot.playerId",
    "alias": "$inputRoot.alias",
    "name": "$inputRoot.displayName",
    "photo": "$inputRoot.profilePhotoUrl"
}
Enjoy!!

Sending Request Body can be other than JSON in API Gateway in AWS

Can you accept a form request e.g. the classic application/x-www-form-urlencoded body content type. Answer is yes.

You could even use application/xml or any other format from your request but you have to tweak some settings.

Default mapping template in response:
{
    "body" : $input.json('$')
}

Now, if you send a typical application/JSON body…

{
    "foo": "bar"
}

you’ll get is a JSON object under the body key:

{
    "body" : {
       "foo": "bar"
    }
}


Now if you send a different format, say some XML you’ll receive the body key as a string:

{
    "body" : "my request body"
}

However, if you do so then you need your lambda to do the parsing further.

And Ah! ofcourse you need to redeploy your Api gateway after above changes.

Cheers :)