You are viewing the preview version of this book
Click here for the full version.

Cognito

Code example

Implementation here.

Applications usually need a way to store users and to handle logins. In the AWS ecosystem the primary choice for this is Cognito, though AppSync support other providers as well as we've discussed in the Authorization providers chapter.

User pool settings

The first step is to create a user pool and configure it:

resource "aws_cognito_user_pool" "pool" {
  name = "social-network-${random_id.id.hex}"
  admin_create_user_config {
    allow_admin_create_user_only = true
  }
  account_recovery_setting {
    recovery_mechanism {
      name     = "verified_email"
      priority = 1
    }
  }
}

The above configuration is good only for simple demos: for example, it does not allow users to sign up to the service. But in our case with fixed users, it's sufficient.

User Pool Client

To allow logins, a user pool also needs a client. This defines the way users can log in, for example, what flows and redirect URLs are allowed.

A simple client:

resource "aws_cognito_user_pool_client" "client" {
  name         = "client"
  user_pool_id = aws_cognito_user_pool.pool.id

  allowed_oauth_flows                  = ["code"]
  callback_urls                        = [
"https://${aws_cloudfront_distribution.distribution.domain_name}"
  ]
  logout_urls                          = [
"https://${aws_cloudfront_distribution.distribution.domain_name}"
  ]
  allowed_oauth_scopes                 = ["openid"]
  allowed_oauth_flows_user_pool_client = true
  supported_identity_providers         = ["COGNITO"]
}

Hosted UI

Finally, we'll also add a hosted UI. This gives a bare-bones but functional login form that the frontend can redirect to. In a mature application it's better to implement the login in the app itself rather than relying on the AWS-provided UI. But for a quick demo, it's entirely sufficient.

The default Cognito login page

The resource for that:

resource "aws_cognito_user_pool_domain" "domain" {
  domain       = "social-network-${random_id.id.hex}"
  user_pool_id = aws_cognito_user_pool.pool.id
}

AppSync configuration

There is more, but you've reached the end of this preview
Read this and all other chapters in full and get lifetime access to:
  • all future updates
  • full web-based access
  • PDF and Epub versions