Authentication with Cognito
Authentication can be managed with AWS Cognito and invoked utilizing the AWS SDK.
These steps will setup an unauthenticated identity pool. Implementing an authentication flow can be done with a setup similar to these instructions.
- Go to Cognito
- If this is your first time, click Manage Identity Pools
- Create new identity pool
- Give your identity pool a name
- Click the Enable access to unauthenticated identities checkbox.
- Create pool
- Select View Details
- Edit the unauthenticated Policy for a new IAM Role with the policy below
- Replace the
arn:
values in theResource
array with the ARNs of your Lambdas.- These will be in the form of
app-name-compute-function-name
i.e. "cognito-tutorial-compute-get-items-by-type". - Click the Lambda name and copy the
Function ARN
on the next page.
- These will be in the form of
- Allow
- Save the Identity Pool ID
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "mobileanalytics:PutEvents", "cognito-sync:*" ],@ "Resource": "*" }, { "Effect": "Allow", "Action": [ "lambda:InvokeFunction", "lambda:InvokeAsync" ], "Resource": [ "arn:my-arns-here" ] } ] }
The above policy is more permissive than most applications will require. Limit the policy to only what is necessary.
Test Your Lambda
Test your Cognito setup here:
Supply your Cognito Identity Pool ID, region and press submit. The returned payload will be displayed below.
Lambda Results displayed here
AWS Javascript SDK Example
This example utilizes the AWS SDK for Javascript to invoke the supplied function.
The AWS SDK is officially supported for a variety of programming languages.
A simple non-parameterized example:
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.854.0.min.js"></script>
function invoke_lambda () { AWS.config.region = 'region' AWS.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId: "identity-pool-value", }); lambda = new AWS.Lambda({ region: "region", apiVersion: '2015-03-31' }); var pullParams = { FunctionName: "function-name", InvocationType: 'RequestResponse', LogType: 'None', Payload: "payload" }; lambda.invoke(pullParams, function(err, data) { { if (err) { // handle error } else { // handle data.Payload } } }) }
Change the placeholders above to the appropriate values for:
AWS.config.region
IdentityPoolID
region
FunctionName
Payload
Then call invoke_lambda()
.