AWS: getting limited IAM credentials for DynamoDB without JS SDK - amazon-web-services

What I want to achieve:
My case described in this article but I do not want to use SDK on my webpage - I want to keep my app simple and fast, but as it turned out - it is hard to find an example that does not use SDK. I stumped with http call from which I need to get limited IAM credentials for DynamoDB. In my investigation of the documentation, I found method GetCredentialsForIdentity, description:
Returns credentials for the provided identity ID. Any provided logins
will be validated against supported login providers. If the token is
for cognito-identity.amazonaws.com, it will be passed through to AWS
Security Token Service with the appropriate role for the token.
But on this page not mentioned url for that endpoint. I tried
https://cognito-idp.us-east-1.amazonaws.com
https://cognito-identity.us-east-1.amazonaws.com
https://<mydomain>.auth.us-east-1.amazoncognito.com
I getting 400 error now, maybe because of incorrect endpoint url. My current code:
fetch('https://cognito-identity.us-east-1.amazonaws.com', {
'method': 'POST',
'headers': {
'Content-Type': 'application/x-amz-json-1.1',
'X-Amz-Target': 'AWSCognitoIdentityService.GetCredentialsForIdentity',
},
'body': '{"IdentityId": "us-east-1:<GUID of the user>"}'
});
1) What is the http endpoint?
2) Am I digging in the right direction?

Correct endpoint is
https://cognito-identity.us-east-1.amazonaws.com
according to this page.
Also, I found that I need to provide not a sub from id_token but firstly GetId of the user.

Related

How to convert Amazon MWS credentials to SP-API creds

Here are the seemingly clear instructions from Amazon.
Simply send the following: sellingPartnerId, developerId, and mwsAuthToken
I do this with httparty like so:
query = {
sellingPartnerId: "A3Kxxxxx",
developerId: "753xxxx",
mwsAuthToken: "amzn.mws.8abxxxxx-xxxx-xxxx-xxxx-xxxxxx",
}
and then
send = HTTParty.get("https://sellingpartnerapi-na.amazon.com/authorization/v1/authorizationCode",
query: query
)
This returns the following error:
{"errors"=>
[{"message"=>"Access to requested resource is denied.",
"code"=>"MissingAuthenticationToken"}]}
I've adjusted the call everyway I've seen. I've read the following articles:
This
This
Paged through the 695 issues on github for this API and still no luck.. I've adjusted my query to this with no luck either:
query = {
grant_type: "client_credentials",
sellingPartnerId: "A3K98Oxxxxxx",
developerId: "753xxxxxxxx",
mwsAuthToken: "amzn.mws.8abxxxxxxx-xxxx-xxxx-xxxx-xxxxxxx",
client_id: "amzn1.application-oa2-client.xxxxxxxxxxxxxxxxxxxxxxxx",
client_secret: "a473e76XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
scope: "sellingpartnerapi::migration"
}
Nothing I've tried has worked.. Any suggestions? Has anyone actually migrated their MWS to SP-API credential successfully?
Unfortunately the specific Amazon docs that you link to don't tell the whole story. There are a few other requirements you'll need in order to get the authorizationCode response that you're looking for:
Amazon OAuth Token
You'll need an access token from Amazon's OAuth API (an entirely different API). You can use the grantless workflow for this, since in your case the user hasn't actually authorized the SP-API yet:
POST https://api.amazon.com/auth/o2/token
body: {
grant_type: 'client_credentials',
scope: 'sellingpartnerapi::migration',
client_id: 'amzn1.application-oa2-client.xxxxxxxxxxxxxxxxxxxxxxxx',
client_secret: 'a473e76XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
}
This will return an access_token that you'll need for your actual migration request to https://sellingpartnerapi-na.amazon.com/authorization/v1/authorizationCode. The response will look something like:
{
"access_token": "Atc|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"scope": "sellingpartnerapi::migration",
"token_type": "bearer",
"expires_in": 3600
}
Important: Take the access_token value from that response and add it as an x-amz-access-token header to your /authorization/v1/authorizationCode request.
Sign Your Request
This is the actual reason behind the error you're receiving. An unsigned request will not include the "authorization token" that you're being prompted for.
You'll need to sign your request using Amazon's SigV4 signing mechanism. It looks like you're using Ruby (HTTParty), so you can use the aws-sdk's Aws::Sigv4::Signer for this. You'll need to have setup IAM credentials as documented in the generic developer guide, and those credentials being provided to your Aws::Sigv4::Signer somehow (hardcoding, env vars, Aws::SharedCredentials, etc.)
Request signing will result in a few proprietary headers being added to your request. Once this is done, you should have all that you need to make the request successfully.

AWS: Cognito integration with a beta HTTP API in API Gateway?

Amazon Web Services introduced a beta release of HTTP API as a new product on API Gateway early last month. Its authentication is managed using JSON Web Tokens and configured with a form asking for
"Name of the Authorizer"
"Identity Source... a selection expression that defines the source of the token"
"Issuer URL"
I'm not very familiar with authentication protocols at all or what these form fields are asking, and currently the documentation from AWS on how to configure this to work with Cognito is sparse. I'm not totally comfortable configuring this without guidance due to my lack of experience. Another Stack Overflow user seemed to have a similar issue but didn't get an answer.
AWS is using JWT Bearer Grant for this purpose.
Draft Specification here.
It allows HTTP API Gateway to accept JWT Tokens in the incoming Authorization HTTP header containing a self-contained JWT access token issued by third-party authorization servers (like Cognito, Azure AD, etc).
API Gateway validates the incoming JWT Token by matching the 'iss' value with the issuer URL to see if it can trust this token.
Try with these values.
Name of the authorizer: Registered client name in your Cognito User Pool .
Identity Source: Leave it as default, $request.header.Authorization .
Issuer URL: Check the metadata URL of your Cognito User Pool (construct the URL in this format :: https://cognito-idp.[region].amazonaws.com/[userPoolId]/.well-known/openid-configuration :: look for a claim named "issuer". Copy its Value and paste it here.
Audience: Client ID of your Registered client in Cognito
Good Luck!
cheers,
ram
Used #ram answer to get through, and was able to implement this
1.Name of the authorizer:
AWS Cognito > User pools > App Integration > App client settings > App client :
Example : xxxxxx_app_clientWeb
2.Identity Source : $request.header.Authorization
3.Issuer URL
construct the URL to get Cognito user pool metadata ( https://cognito-idp..amazonaws.com//.well-known/openid-configuration)
Example :
https://cognito-idp.us-east-1.amazonaws.com/us-east-1_FcgSrx2141/.well-known/openid-configuration
open the URL and you will see a json
take the "issuer" value
Example :
"issuer":"https://cognito-idp.us-east-1.amazonaws.com/us-east-1_FcgSrx2141"
Take: https://cognito-idp.us-east-1.amazonaws.com/us-east-1_FcgSrx2141
4. Audience: AWS Cognito > User pools > App Integration > App client settings > App clientID
Example :
ID 9sptej55gii5dfp08ulplc343
Take: 9sptej55gii5dfp08ulplc343
This video explains the whole process and configuration like no other.
https://www.coursera.org/lecture/building-modern-java-applications-on-aws/use-amazon-cognito-to-sign-in-and-call-api-gateway-s226R
I am thankful that the video is public.
Note: (As far as I know) The course is from AWS but offered to the public through different MOOC websites (not just this one).
Once you have read & played enough, you will start seeing the gems within the details.
Token for example, is mentioned in many docs, but it can be Access / Id / Refresh Token. If you don't realize about this you can be wasting your time.
For example the "Implicit grant" doesn't provide a Refresh-Token, so you cannot renew your Access-Token and trying to do it is useless.

AWS Amplify React GET request error - missing authentication token

I am using AWS Amplify in my react app to call my API hosted in API Gateway with AWS_IAM authorization. When I set authorization to NONE, everything works fine in my react app.
However, when I set authorization to AWS_IAM and execute my API using API.get() from Amplify like the code below:
const notes = await API.get('notes', '/notes', init);
I get an error message like:
{
"message": "Missing Authentication Token",
"err": "missing auth"
}
So I tried to use aws-api-gateway-cli-test to test my API gateway. Through the script, I was able to get a valid credential, get authenticated and correct response. I have also tried the POSTMAN with my admin credentials and it worked as well.
After doing some research, I saw people referring this to CORS issue. I have double checked my API gateway settings and confirmed that I have enabled CORS. The same issue persists.
Through the debugging feature of aws-amplify, I was able to see the signing process in my Chrome inspector. The signing process was performed properly with some accessKey and secretKey. I pulled those keys out of the inspector into my POSTMAN and tried to get.
These credentials are not valid and I received the following error message:
{
"message": "The security token included in the request is invalid.",
"err:": "default"
}
Update: I forgot to copy session token into POSTMAN. Now with all credentials generated by my app I am able to get correct result from my API in POSTMAN. Just not in my app.
At this point, it is pretty obvious to me that it is an auth problem. However, I have been using aws-amplify for sign-in and get process. Pretty sure the signing process is done by amplifying behind the scenes.
I have spent 3 days on this problem and basically tried everything... Any ideas on why it doesn't work?
P.S. A lot of people have suggested that typos in the invoke URL could lead to this issue. I have double checked and there is no typo. Below is my amplify configure code:
Amplify.configure({
Auth: {
mandatorySignIn: true,
region: config.cognito.REGION,
userPoolId: config.cognito.USER_POOL_ID,
identityPoolId: config.cognito.IDENTITY_POOL_ID,
userPoolWebClientId: config.cognito.APP_CLIENT_ID
},
Storage: {
region: config.s3.REGION,
bucket: config.s3.BUCKET,
identityPoolId: config.cognito.IDENTITY_POOL_ID
},
API: {
endpoints: [
{
name: "notes",
endpoint: config.apiGateway.URL,
region: config.apiGateway.REGION
}
]
}
});
Just resolved my problem - I have had Authorization settings for OPTIONS method to be AWS_IAM under Resources in API Gateway. However when my browser send a request it will send one to OPTIONS first to check for certain headers without the credentials in this request.
Since I set OPTIONS with IAM authorization, the OPTIONS method then checked against IAM with this request without my credentials. This is why I received "Missing Authentication Token".
The problem was this in my case:
import { Auth } from 'aws-amplify';
import { API } from 'aws-amplify';
I know, I now it's banal. This why I should't code when I am exausted.

How to get the accesstoken from alexa after account linking with azure AD

I tried to connect my Alexa AWS Lambda function (node.js 6.10) with Azure Activ Directory to my Azure-Cloud-API. After reading the documentation from amazon and many tutorials I have now a working Account Linking. That means, I can link the Account of the Skill inside the Alexa-App on my smartphone.
AccountLinking for my Custom Skill:
{Data from my azure portal}
Authorization Grant Type: Auth Code Grant
Authorization URI: {OAUTH 2.0 AUTHORIZATION ENDPOINT}
Access Token URI: {OAUTH 2.0 TOKEN ENDPOINT}
Client ID: b9c6[...]bc60 {Application ID}
Client Secret: {Client Secret}
Client Authentication Scheme: Credentials in request body
scope: openid
domain: empty
redirect urls: --> In Azure portal as ALLOWED TOKEN AUDIENCES and Reply URLs defined
In my aws lambda function I get the event request from alexa like the documentation says with properties for version, session, context, request...
My understanding of the documentation is, that the token I need for the Azure-Cloud-API-Request should be here: session.user.accessToken
But this token doesn't look like the one I need and after my test runs I get always "Unauthorized" back.
The Token looks something like this and is 1252 characters long:
AQABAAAAAADX8GCi6Js6SK82TsD2Pb7rqGN56iHT_YSxlSr1RAdXucGs0S3ykOaw0XZ1WnjJotqZAn9BH7agRbP0VQv2rnJuRw_aJil7 [...] JIEO2Ap4wuG-tTwiSmZBfbLhyYtwQmxLAkqiLApqFmBYcyu-dnzlVV4liDGyTQ7gAXufd3zt7QGmi3UfP1aL9f5NBeXbmxnU6FHRzF10QZa19pTQgNTtIK8oIAA
If I configure postman and send a request to the azure activ directory I get a accessToken like this (1168 characters long):
eyJ0eXAiOiJKV1QiLCJhbGc [...] Ezbk5aY2VEYyJ9.eyJhdWQiOiJodHRwczovL21ldGVvcmEtYXBwLmF [...] kY5MWVUUXdBQSIsInZlciI6IjEuMCJ9.KJco47-FdJ_eeqv38LL [...] YK_4JqCRDw
This one looks like a jwt-token and if I copy this token directly in my aws lambda function and use this one for the Azure-Cloud-API-Request it works (until the token expires).
Now I'm not sure if there is a problem in my configuration of the account linking? Or do I have to do something with the token from alexa to get the real one? Or is the real token somewhere else and I have to fetch it there?
Thanks a lot for your help!
Amazon Documentation "Alexa Skills Kit":
https://developer.amazon.com/docs/custom-skills/link-an-alexa-user-with-a-user-in-your-system.html
EDIT (Solution) 11.06.2018
Authorization Grant Type: Auth Code Grant
Authorization URI: {OAUTH 2.0 AUTHORIZATION ENDPOINT} + ?resource= + {Application ID}
Access Token URI: {OAUTH 2.0 TOKEN ENDPOINT}
Client ID: b9c6[...]bc60 {Application ID}
Client Secret: {Client Secret} App>Settings>Keys new Key with expiration date = 2 years
Client Authentication Scheme: Credentials in request body
scope: empty
domain: empty
redirect urls: --> In Azure portal as ALLOWED TOKEN AUDIENCES and Reply URLs defined
It sounds like you haven't completed the account linking sequence for your skill. After setting the account linking configuration you need to open the Alexa app (on your phone or https://alexa.amazon.com) and go to your new skill and link your account. Once that is successful you will get a token in request.Session.User.AccessToken.
The blog post: https://blogs.msdn.microsoft.com/premier_developer/2017/12/09/amazon-alexa-skills-authenticated-by-azure-active-directory-and-backed-by-asp-net-core-2-0-web-api-hosted-on-azure/ needs to be updated with the following:
You can ignore the sections about the "front end" app registration.
In Alexa account linking section update URLs to use login.microsoftonline.com instead of login.windows.net
ClientId to be the Application Id of the "back end" app registration
The ?resource= has to be set and has to be the same as the audience parameter for the JWT bearer options. This is ClientId if you use the .Net Core 2.0 template in Visual Studio.
The client secret (key) that is used can not be one that "Never Expires". Use a 1 or 2 year duration.
In addition to Nate's answer and following the addition of ?resource= to the Authorisation URI, I had to give the API permission Azure Active Directory Graph > User.Read on the App Registration and Grant Admin Consent to it.
Without this permission, the account linking would throw an error. If you have similar issues, try your OAuth values with Postman and check the Postman Console for error messages

Missing Authentication Token while accessing API Gateway?

I am trying to call a Lambda Function through AWS API Gateway.
When I mention Authentication type NONE it works fine but API become public and anyone with url can access my API.
To make API call secure, I am using Authentication type AWS_IAM and
also attached AmazonAPIGatewayInvokeFullAccess policy to my user but getting this error:
{ message: "Missing Authentication Token"}
I don't know what I am missing here.
I've lost some time for a silly reason:
When you create a stage, the link displayed does not contain the resource part of the URL:
API URL:
https://1111.execute-api.us-east-1.amazonaws.com/dev
API + RESOURCE URL
https://1111.execute-api.us-east-1.amazonaws.com/dev/get-list
The /get-list was missing
And of course, you need to check that the method configuration looks like this:
I think you are directly trying to access API link, this won't work because API is secured using IAM role and you must provide AWS authentication i.e Access key and Secret key.
Use the Postman Chrome extension to test your API:
http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-use-postman-to-call-api.html
I just had the same issue and it seems it also shows this message if the resource cannot be found.
In my case I had updated the API, but forgotten to redeploy. The issue was resolved after deploying the updated API to my stage.
Make sure you are clicking on the specific Resource first in the Stages tree, as that will populate a URL with the full path to the resource (rather than just the root path):
For other causes, see http://www.awslessons.com/2017/aws-api-gateway-missing-authentication-token/
Looks like (as of April 2019) AWS API Gateway throws this exception for a variety of reasons - mostly when you are hitting an endpoint that API Gateway is not able to reach, either because it is not deployed, or also in cases where that particular HTTP method is not supported.
I wish the gateway sends more appropriate error codes like HTTP 405 Method not supported or HTTP 404 not found, instead of a generic HTTP 403 Forbidden.
Found this in the docs:
If the AWS_IAM authorization were used, you would sign the request using the Signature Version 4 protocols.
Signing request with Signature Version 4
You can also generate an SDK for your API.
How to generate an SDK for an API in API Gateway
Once you've generated the SDK for the platform of your choice, step 6 mentions that if you're using AWS credentials, the request to the API will be signed:
To initialize the API Gateway-generated SDK with AWS credentials, use code similar to the following. If you use AWS credentials, all requests to the API will be signed. This means you must set the appropriate CORS Accept headers for each request:
var apigClient = apigClientFactory.newClient({
accessKey: 'ACCESS_KEY',
secretKey: 'SECRET_KEY',
});
I try all the above, if you did all steps in the above answers, and you not solve the problem, then:
on the left menu, hit the "Resources"
in the right to "Resources", hit the api method that you want to test, like "POST/GET etc)
hit the "ACTION" list (it's above to the API method in step 2
select "DEPLOY API" (please do it, even you already deploy yours api)
in "deployment stage" select "prod" or what ever you write in yours previous deploy (it will override yours previous deploy
hit deploy
I thing that because of, when I create the "METHOD REQUEST" (see step 2 how to go to this menu) , in "Authorization" I select "AWS_IAM"
after testing api, in aws test option, I try it in "postman"
then I understand the in "METHOD REQUEST" , in "Authorization", I should select "none"
I change it to none, but I thing the AWS, need to deploy it again, as I explain
Make sure you create Resource and then create method inside it. That was the issue for me. Thanks
In my case I missed adding '/' forward slash at the end of api.
Such a silly mistake.
https://le9dq5l9.execute-api.eu-west-1.amazonaws.com/v1/putdoctorinfo/
If you enable AWS_IAM authentication you must sign your request with AWS credentials using AWS Signature Version 4.
Note: signing into the AWS console does not automatically sign your browser's requests to your API.
sometimes this message shown when you are calling a wrong api
check your api endpoint
In my case it was quite a stupid thing.
I've get used that new entities are created using POST and it was failing with "Missing Authentication Token". I've missed that for some reason it was defined as PUT which is working fine.
This error mostly come when you call wrong api end point.
Check your api end point that you are calling and verify this on api gateway.
If you are using an API with endpoint of type PRIVATE, be sure of:
You are invoking the API from within your AWS account (example: from an EC2 instance created in your account)
Put necessary credential (access and secret keys) in the EC2 instance in route ~/.aws/credentials (this route is for linux instances) If IAM user use MFA aws_session_token value will be required too.
Use vpce (vpc endpoint) based URL. Example: curl https://vpce-0c0471b7test-jkznizi5.execute-api.us-east-1.vpce.amazonaws.com/dev/api/v1/status
Your EC2 instance have a security group than allow outbound traffic to another security group owned by the vpce like:
Your vpce security group allow inbound traffic from another security group (previous sg from ec2 instance) owned by the EC2 instance like:
See: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-private-apis.html
I had the same problem which I solved the following way:
GET Method test
https://54wtstq8d2.execute-api.ap-southeast-2.amazonaws.com/dev/echo/hello
Authorization tab ->
• select type(AWS signature)
• Add AccessKey and SecretKey
You must be using Invoke Url to trigger Lambda Function from your browser or POSTMAN... Instead, use the API end point which will be listed in:
select yourLambdaFuntion >> Configuration >> Triggers.
There you can see API end point.
For the record, if you wouldn't be using credentials, this error also shows when you are setting the request validator in your POST/PUT method to "validate body, query string parameters and HEADERS", or the other option "validate query string parameters and HEADERS"....in that case it will look for the credentials on the header and reject the request. To sum it up, if you don't intend to send credentials and want to keep it open you should not set that option in request validator(set it to either NONE or to validate body)
I had the same issue, and fixed it by removing the /dev/ and just put: https://1111.execute-api.us-east-1.amazonaws.com/get-list
I had same issue today because I was using GET instead of POST. Fixed the issues by changing method to POST in postman.
First of all, check whether the API you created in the lamda function is registered with your AWS project or not. For that, go to the API gateway in your AWS console. If it is not registered, register it. This is the main cause of this issue.
You can even see in your aws.export.js file, that there are paths corresponding to your API ['/items'].
Your API must be present there, otherwise it will not append the security token to requests. Just register it in your project cloud-logic in your console for this.
If it's there, then use the above mentioned solution
http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-use-postman-to-call-api.html
To contribute:
I had a similar error because my return response did not contain the 'body' like this:
return {
'statusCode': 200,
'body': "must contain the body tag if you replace it won't work"
}
If you set up an IAM role for your server that has the AmazonAPIGatewayInvokeFullAccess permission, you still need to pass headers on each request. You can do this in python with the aws-requests-auth library like so:
import requests
from aws_requests_auth.boto_utils import BotoAWSRequestsAuth
auth = BotoAWSRequestsAuth(
aws_host="API_ID.execute-api.us-east-1.amazonaws.com",
aws_region="us-east-1",
aws_service="execute-api"
)
response = requests.get("https://API_ID.execute-api.us-east-1.amazonaws.com/STAGE/RESOURCE", auth=auth)
Well for anyone still having the problem and I really feel very dumb after realizing this, but I passed in the url of /items the default one while adding API. But I kept calling the endpoint with /api. Special thanks to Carlos Alberto Schneider, as I realized my problem after reading your post.
According to my experience, please check the following steps:
On API gateway side, make sure you add the correct path and publish the resource at the stage you want. For some url pattern like path parameter(/user/{user_id}) need more attention to have a check.
Make sure you configure the correct options method for this resource, because sometimes it is the CORS that cause this problem.
On Lambda side, make sure you specify the correct handler name as the entrypoint.
Please always check cloudwatch logs of your lambda that can help u identify the problems on your lambda side.
In my case I was trying to do an UPDATE type request but in my AWS SAM template I had a PATCH type request:
Resources:
LambdaFunction:
Type: AWS::Serverless::Function # More info about Function Resource:
# https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: src/
Handler: app.lambda_handler
Runtime: python3.8
MemorySize: 128
Events:
UpdateItem:
Type: Api
Properties:
Path: /my-endpoint
Method: patch
Things to check:
1. In resources, check for Authorization and API Key if these are required.
2. Redeploy the API, new changes might not reflected.
3. Get the url from stages, directly by clicking on the actions like GET, POST, These will contain the full path urls.
I had the same issue even if my access was regional and not private, no authorization on my method neither API. It's turned out that I was calling the root endpoint "https://azerty.execute-api.eu-west-3.amazonaws.com/dev/", which in local return me a json but raised an error. Be sure to call a proper endpoint, such as "https://azerty.execute-api.eu-west-3.amazonaws.com/dev/hello"