This is a Rails application that demonstrates an AWS Cognito User Pool server-side authentication flow using the Cognito Hosted UI. This was extracted from another application that leveraged the Cognito User Pools for minimal user authentication management.
User Sign Up, Sign In, and Sign Out are handled directly with Cognito and the Hosted UI auth forms. The Rails application simply extracts the authentication data from the redirect after an authentication action is performed. Server-side session keys track the Cognito tokens and automatically refresh expired tokens.
There's a demo of this application running at https://cognito-rails-example.herokuapp.com/.
Create a new Cognito User Pool in the AWS console. The following screenshots show the non-default settings I used to create this pool. This is just a minimal example, so you will want to change the settings to match your preferences.
Password policy for this pool is minimally restrictive, match your security org requirements.
We want minimal friction in our sign up form, so we will only collect an email + password for now. You can include any number of attributes in the sign up form. The email will act as the username in our setup.
We need at least one app client for our web app to talk to the API. We'll need to lookup auth codes so enable 'Generate client secret'. The name doesn't really matter so pick anything.
With the app client created, you need to set the app client settings. Set the callback and sign out URLs to match your application. These URLs must match the same redirect URLs used in the application. Also, ensure the authorization code grant is selected and email is in the allowed oauth scopes.
Finally, after the pool is created we will set the domain name that is used for the hosted UI. If this were a production application you would probably want to use your own full domain name instead.
These are the required environment variables for this app:
AWS_COGNITO_APP_CLIENT_ID
AWS_COGNITO_APP_CLIENT_SECRET
AWS_COGNITO_DOMAIN
AWS_COGNITO_POOL_ID
AWS_COGNITO_REGION
- Track a user session through signup/signin for funnel analytics.
- Multiple identify providers (Facebook, Google, etc)
- Expire old sessions periodically
- Refresh active Cognito sessions ahead of their expiration to avoid blocking on the next request
The omniauth-cognito-idp provides an alternative approach that leverages the OmniAuth framework to build a Cognito aware oauth2 middleware.