Skip to content

Cognito User Pool with .NET core app using OpenId Connect

Overview

This walkthrough configures an ASP.NET web app hosted on AWS to AWS Cognito Picture 1

Topics covered

In this walk-through, you'll build the following: - An Amazon Cognito User Pool to authenticate, store and manage users - Configure and deploy an ASP.NET Core Web App that will be hosted using AWS Elastic Beanstalk

Pre-requisites

  • An AWS account with Administrative rights
  • Visual Studio 2017 Community Edition or better with the AWS toolkit installed
  • Select the Canada (Central) Region
  • Go to EC2 and build new instance based on this AMI: ami-003d123f6bdf74c48
  • Select m5.large and use Administrator password VSToolkit@reInvent

Task 1. Create Amazon Cognito User Pool

In this task, you will create and configure User Pool using the AWS Management console.

Step 1. Open the AWS Console, navigate to the Cognito UI and click Manage User Pools Picture 2

Step 2. Next click Create a user pool Picture 3

Step 3. Enter "Demo App Users" for the Pool name and click Review Defaults Picture 4

Step 4. Click on Add app client... Picture 5

Step 5. Click on Add an app client Picture 6

Step 6. Enter the following and click Create app client - App client name: DemoAppClient - Uncheck Generate client secret checkbox

Picture 7

Step 7. Click Return to pool details Picture 8

Step 8. Click Create pool Picture 9

Step 9: Copy the Pool ID and paste it in a text editor, we’ll use it when we configure the .Net App Picture 10

Step 10: Go to App client settings under App Integration, copy the ClientID and paste it in a text editor, we’ll use it when we configure the .Net App Picture 11

Step 11: Set following properties - Check Cognito User Pool under Enabled Identity Providers - Set Calllback and Sign out URLs

Note: You will need to specify callback and signout URLs. These will correspond to an AWS Elastic Beanstalk deployed application you will configure further on in this lab. The Elastic Beanstalk URLs is based on the region in which it is created. For the purposes of this lab we are using the Canada Central region (ca-central-1), please make a note of which region you are working in when creating URLs and configuring applications. You will also need to prepend the url with your own username-prod (example: janedoe-prod) to ensure uniqueness.

Callback URL: https://openidconnectapp-username-prod.ca-central-1.elasticbeanstalk.com/signin-oidc-aws

Signout URL: https://openidconnectapp-username-prod.ca-central-1.elasticbeanstalk.com/account/signedout

Please make note of these URLs as we will use them throughout the rest of the lab. - Under Allowed Oauth Flows check Authorization code grant - Under Allowed OAuth Scopes check openid and profile - Click Save changes

Picture 12

Step 12: On the left hand side of the console window click Domain Name under App Integration. - Set the Domain prefix to openidconnect-[username>], eg: openidconnect-janedoe - Click on Check availability to ensure the domain name is available Picture 13

  • Click on Save changes
  • Copy the domain url and save it in text editor
    • Eg: https://openidconnect-username.auth.ca-central-1.amazoncognito.com

Step 14: On the left side of the console click on Users and Groups under General Settings Picture 14

Step 15: Click Create User Enter the following details: - Username: testuser - Uncheck Send an invitation to this new user? - Temporary password: Password@1 - Phone Number: blank - Uncheck Mark phone number as verified? - Email address: testuser@testcorp.com - Check Mark email as verified?

Task 2: Create a KeyPair

Step 16: Navigate to AWS Console and go to EC2 dashboard Step 17: In the left navigation, under Network and Security click on Key Pairs Picture 15

Step18: Click on Create Key Pair - Enter DemoApp in the Key pair name

Step19: Save the key pair file on your system, we will use it when deploying Elastic Beanstalk

Task 3: Create .NET Core Application

In this task you’ll be creating an ASP.NET Core Web App project that will run on Elastic Beanstalk. This is a sample project to demonstrate the seamless integration of Amazon Cognito

Prerequisites

  • Visual Studio 2017
    • Please follow this guide to install Visual Studio community edition
  • AWS Toolkit for Visual Studio
    • https://aws.amazon.com/visualstudio

Note: You can do all this on Mac OS X or Linux also. Once you have the .NET Core framework installed, you can install the AWS templates with the dotnet new command:

Bash @:~$ dotnet new -i Amazon.Lambda.Templates::*

Step 20: Download the project from S3 bucket - In the address bar of the internet explorer, enter: https://bit.ly/2PGtUfs

  • When the Internet Explorer dialog box appears, click Save.

Info: This bucket contains the .NET Core App OpenIDConnect solution. This is a simple web application to demonstrate Amazon Cognito integration with ASP.NET Core App using OpenIdConnect.

This sample shows how to use the OpenID Connect ASP.NET Core middleware to sign-in users from a Amazon Cognito User Pool. The middleware is initialized in the Startup.cs file by passing it the Client ID of the app and the URL of the Amazon Cognito IDP where app is registered, which is read from the appsettings.json file. The middleware takes care of: - Downloading the Amazon Cognito metadata, finding the signing keys, and finding the issuer name for the tenant. - Processing OpenID Connect sign-in responses by validating the signature and issuer in an incoming JWT, extracting the user's claims, and putting the claims in ClaimsPrincipal.Current. - Integrating with the session cookie ASP.NET Core middleware to establish a session for the user. You can trigger the middleware to send an OpenID Connect sign-in request by decorating a class or method with the [Authorize] attribute or by issuing a challenge (see the AccountController.cs file):

Step 21: Unzip the file in the instance which has Visual Studio 2017 installed.

Step 22: Open Visual Studio 2017, click File >Open>Project/Solution.

Step 23: Go to the path where you have the OpenIdConnect.sln file, click Open Picture 16

Step 24: Right click on the project and build it and it should build successfully without any errors.

Step 25: In the appsettings.json file, under AWSCognito provide values for: - Region: Region in which Amazon User Pool was created Eg: ca-central-1 - Domain, ClientID and PoolID that you recorded earlier from the Amazon Cognito

Picture 17

Task 4. Deploy the sample ASP.NET app to AWS

In this task you will deploy the sample ASP.NET app to AWS.

Step 26: From the Build menu select Rebuild Solution and then right-click the project and select Publish to AWS Elastic Beanstalk Picture 18

Step 27: Select the region you configured Cognito Pool in and leave the "Create a new application environment" and click Next Picture 19

Step 28: Select openidconnectapp-prod from the Environment dropdown, Edit the URL field to show: openidconnect-username-prod. Check availability for the URL and then click Next. The wizard will automatically append the region information during deployment. So if we enter: openidconnectapp-username-prod it will deploy as https://openidconnectapp-username-prod.ca-central-1.elasticbeanstalk.com which should match the domain name of the callback and signout URLs you created in step 11.

Picture 20

Step 29: Keep the default value in container type, select m4.large as instance and in the Key pair dropdown select the DemoApp keypair which was created in Task 2. Picture 21

Step 30: Leave the default Role Settings and then click Next Picture 22

Step 31: Leave the default Build and Deployment Setting, click Next and then click Deploy on the final screen Picture 23

Step 32: Once the Beanstalk publishing process is complete navigate to the AWS console, open the AWS Elastic Beanstalk UI

Note: we'll need to wait a few minutes for Beanstalk to finish provisioning the environment, occasionally refresh the page and once the tile is green you can click on it to view the details of the environment

Picture 24

Step 33: Navigate to the EC2 Dashboard, you will need to modify the security group to allow incoming traffic on port 443 - For the Instance that Beanstalk deployed on our behalf let's add the 443 and 3389 port rules

Step 34: Update the Security Group for this server to allow traffic on port 3389 and 443, Click on the first security group next to Security groups to modify it. Picture 26

Step 35: Go to Inbound tab and click on Edit

Step 36: Add RDP and HTTPS rules, make sure the IP address is set to 0.0.0.0/0, ::/0 Picture 27 - Click on Save

Step 37: Go back to the Ec2 instance and copy the Public IP address, the Windows Password and then RDP into the server. - To grab the password, you’ll have to provide the keypair which was created in Task 2. Picture 28

  • Browse to the key pair file you downloaded and click on Decrypt Picture 29

  • Copy the password onto a text editor

Step 38: RDP into the server using public IP address and password that you copied in the previous step.

Step 39: Once on the server, open a Powershell prompt (as an administrator) and execute the following command to generate a self-signed SSL certificate, make sure to use the elastic beanstalk hostname you copied in step 32 New-SelfSignedCertificate -DnsName "openidconnectapp-username-prod.ca-central-1.elasticbeanstalk.com" -CertStoreLocation "cert:\LocalMachine\My"

Picture 30

Step 40: From the server click on the windows icon, then expand the Windows Administrative Tools folder and click on Internet Information Services (IIS Manager) Picture 31

Step 44. Expand the server name on the top left and expand the Sites folder, single-click the Default Web Site and then click Bindings... Picture 32

Step 45. Click Add to add a new binding, in the Add Site Binding dialog make sure https is selected, All Unassigned for the IP address, select the self-signed SSL Certificate we created in step from the SSL certificate dropdown, click OK and then close the Site Bindings dialog Picture 33

Step 46. Sign out of the server Picture 34

Task 5: Test the application

Step 49. Now we are ready to browse to the site and test our configuration, open a private or incognito browser window (this helps to prevent any automatic sign-in behaviors and/or cookies from altering any behaviors) and browse to the URL that you created in step 10

Note: the self-signed SSL certificate that we created earlier is not trusted by your computer so we would expect to see the security warning, click on Advanced and then Click on Add Exception https://openidconnectapp-username-prod.ca-central-1.elasticbeanstalk.com

Picture 35

  • On the top right of the screen click Sign in
  • Enter the test username: testuser
  • Enter the test user password: Password@1 Picture 36

  • This will prompt for password change so enter new password and login Picture 37

  • Once logged in, you’ll see all the claims associated with the user. Picture 38
  • Click on Sign Out to sign out the user Picture 39