/ coding

Mobile Authentication System Using Lambda and AWS API Gateway

How to set up AWS API Gateway in order to use LambdAuth with AWS Cognito

This was created to supplement a previous post, see AWS Cognito in Swift. AWS Lambda is a low cost efficient way to run back-end scripts without the need to host a virtual server. AWS charges based on the number of times your run the script and how much data throughput is used. This can also be used as a back-end authentication service, and one open source system has been designed already called LambdAuth. However, in order to use it as your back end system, you must create an API for it, because of the way the AWS SDK is built. Fortunately, AWS also has a service for this, API Gateway.

Set up API Gateway

Login to your AWS console and in services, click on API Gateway. Click Create API and name your service. Create a new resource (under the root /) and name it whatever you want (probably something like "login"). Under that, create a GET method. For integration type, select Lambda Function and select the region, and type the Lambda function name, then click Save and Ok.

Next, you'll want to add some method request headers. This is one way to pass your email and password when you login. With your new method selected in the column on the left, you'll see a map, click the link in the box that says Method Request. Then, under HTTP Request Headers, add email and password. Then click Deploy. Follow the steps to deploy and test your API, and retrieve the endpoint URL. AWS API Gateway

API Gateway

In your Swift code

Now, in your identityProvider class you will set these headers before you post to your API url (which I stored in a swift file at Constants.loginUrl.value):

override func refresh() -> AWSTask! {
    let task = AWSTaskCompletionSource()
    let request = AFHTTPRequestOperationManager()
    request.requestSerializer.setValue(email, forHTTPHeaderField: "email")
    request.requestSerializer.setValue(password, forHTTPHeaderField: "password")
    request.GET(Constants.loginUrl.value, parameters: nil, success: { (request: AFHTTPRequestOperation!, response: AnyObject!) -> Void in
        // The following 3 lines are required as referenced here: http://stackoverflow.com/a/26741208/535363
        self.logins = [self.developerProvider: self.email]
        // Get the properties from my server response
        let identityId = response.objectForKey("identityId")as! String
        let token = response.objectForKey("token")as! String
        // Set the identityId and token
        self.identityId = identityId
        self._token = token
        }, failure: { (request: AFHTTPRequestOperation?, error: NSError!) -> Void in
    return task.task