Cognito

Get your Cognito Credentials

To integrate with Cognito, you need to set up a User Pool and an App client in the Amazon Cognito Console.

Follow these steps:

  1. Go to the Cognito Console and create a User Pool.
  2. Under App clients, create a new App client (note the Client ID and Client Secret if enabled).
  3. Go to Domain and set a Cognito Hosted UI domain (e.g., your-app.auth.us-east-1.amazoncognito.com).
  4. In App client settings, enable:
    • Allowed OAuth flows: Authorization code grant
    • Allowed OAuth scopes: openid, profile, email
  5. Add your callback URL (e.g., http://localhost:3000/api/auth/callback/cognito).
  • User Pool is required for Cognito authentication.
  • Make sure the callback URL matches exactly what you configure in Cognito.

Configure the provider

Configure the cognito key in social_providers key of your auth instance.

config/auth.rb
require "better_auth"

auth = BetterAuth.auth(
secret: ENV.fetch("BETTER_AUTH_SECRET"),
base_url: ENV.fetch("BETTER_AUTH_URL", "http://localhost:3000"),
social_providers: {
cognito: BetterAuth::SocialProviders.cognito(
  client_id: ENV.fetch("COGNITO_CLIENT_ID"),
  client_secret: ENV.fetch("COGNITO_CLIENT_SECRET"),
  domain: ENV.fetch("COGNITO_DOMAIN")
)
}
)

Sign In with Cognito

To sign in with Cognito, use the auth.api.sign_in_social function from the client.

server.rb
response = auth.api.sign_in_social(
body: {
provider: "cognito",
callback_url: "/dashboard",
error_callback_url: "/login",
disable_redirect: true
}
)

redirect_url = response.fetch(:url)

Additional Options:

  • scope: Additional OAuth2 scopes to request (combined with default permissions).
    • Default: "openid" "profile" "email"
    • Common Cognito scopes:
      • openid: Required for OpenID Connect authentication
      • profile: Access to basic profile info
      • email: Access to user’s email
      • phone: Access to user’s phone number
      • aws.cognito.signin.user.admin: Grants access to Cognito-specific APIs
  • Note: You must configure the scopes in your Cognito App Client settings. available scopes
  • get_user_info: Custom function to retrieve user information from the Cognito UserInfo endpoint.

For more information about Amazon Cognito's scopes and API capabilities, refer to the official documentation.

On this page