How to Set up Account Linking in Amazon Alexa with Amazon Cognito OAuth2 Authorization Grant | by Chathurangi Shyalika | Towards Data Science

Amazon Alexa, is the virtual assistant AI technology developed by Amazon which was initially released in 2014. It’s one of the most creative designs by Amazon so far.
Alexa awesomely performs activities like voice interaction, music playback, making to-do lists, setting alarms, streaming podcasts, providing weather, traffic, sports, and other real-time information, such as news and also it can control several smart devices.
According to Amazon’s Developer site, the Alexa Voice Service (AVS) lives in the cloud. Amazon’s AVS is an Intelligent Voice Recognition and Natural Language Understanding (NLU) service. Alexa Voice Service (AVS) attempts to mimic real human-to-human conversations. The service can be used to voice-enable any connected device that has a microphone and speaker. Alexa provides her services to public via components named as “Skills”.
“Alexa is always getting smarter with new capabilities through machine learning,”
-Amazon’s Developer site says.
In this blog post, I’m going to explain about Alexa Account Linking.
Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.
Account linking enables custom skills to connect the skill user’s Amazon identity with the identity in a different system. It also allows your skill to securely authenticate user with services. Once the connection between the skill and external user account is established, the skill can perform operations with that account on behalf on the user.
Account linking uses OAuth 2.0. OAuth 2.0 servers support two protocols for initiating a secure access token exchange: Authorization Code Grant and Implicit Grant.
The Amazon Cognito User Pool involves following task flow.
First, the Alexa service provides a current and valid Access Token at run time to Alexa skill. Note that Alexa service is the one who is responsible in managing the refresh tokens and obtaining new access tokens when they expire.Then, the Alexa skill code uses that token to access the user’s profile in the User Pool. Customers will be authenticated directly with the Cognito user portal when linking the skill using the Alexa app.
First, the Alexa service provides a current and valid Access Token at run time to Alexa skill. Note that Alexa service is the one who is responsible in managing the refresh tokens and obtaining new access tokens when they expire.
Then, the Alexa skill code uses that token to access the user’s profile in the User Pool. Customers will be authenticated directly with the Cognito user portal when linking the skill using the Alexa app.
The Amazon Cognito Account Linking process works as follows.
When the customer wants to login to a system the request is initiated with Account Linking. Here, Firstly the authorization link specified by the developer is opened by the app. It is a link to the Cognito User Portal.When redirected, the customer is been interacted with the Cognito login page. User can then provide the necessary login details (username and password) in order to authenticate.When Cognito verifies the customer’s credentials, an authorization code is provided to the app, and that is passed to the Alexa Service.The Alexa Service then provides that code to Cognito. It provides the initial Access Token and Refresh Token to Alexa service in return. Then user can be accessed with the Alexa skill.
When the customer wants to login to a system the request is initiated with Account Linking. Here, Firstly the authorization link specified by the developer is opened by the app. It is a link to the Cognito User Portal.
When redirected, the customer is been interacted with the Cognito login page. User can then provide the necessary login details (username and password) in order to authenticate.
When Cognito verifies the customer’s credentials, an authorization code is provided to the app, and that is passed to the Alexa Service.
The Alexa Service then provides that code to Cognito. It provides the initial Access Token and Refresh Token to Alexa service in return. Then user can be accessed with the Alexa skill.
In order to completely set up this example, you require an AWS Account and an Amazon Developer Account. Optionally, need a Domain, hosted in Amazon Route53.
Follow the below steps in order to continue.
i) Log in to the AWS Management Console and navigate to Amazon Cognito.
Check the AWS region being used by referring to it in the upper right of the AWS Management Console.
Eventhough any region supported by Cognito can be used, Alexa recommends to use one of four regions us-east-1 (N. Virginia), us-west-2 (Oregon), eu-west-1 (Ireland) and ap-northeast-1 (Tokyo).
ii) Click Manage User Pools.
iii) Click Create a user pool.
iv) Enter a Pool name and click Review Defaults.
v) Select Attributes on the left-side menu.
vi) First,let’s see how to set up Email Authentication. So, for that, First select Email address or phone number and choose Allow email addresses.
vii) In the Which standard attributes do you want to require? section, check the following:
Address,Email,Family name,Given name,Phone number
If you want more user details for sign up page, you can add them accordingly.
viii) Click Next Step.
ix) Go to Policies in left panel and enter following configurations and click Save.
x) Select MFA and verifications on the left-side menu and set:
Do you want to enable Multi-Factor Authentication (MFA) to Off and Which attributes do you want to verify? to Email
xi) Click Save Changes and Select App clients on the left-side menu, then click Add an app client.
xii) Enter an App client name. Enter preferred period for Refresh token expiration (days) field.
xiii) Keep Generate client secret box is checked and remaining boxes un-checked. Click Create App Client.
xiv)Select Review on the left-side menu and click Create pool at the base of the page. Once created, message will be prompted saying Your user pool was created successfully.
xv)Now, Notice the left-side menu have changed. Select General settings > App clients on the left-side menu, and select Show Details. You can see the App client id and App client secret generated for the app.
xvi) Select App integration > App client settings on the left-side menu. Under Enabled Identity Providers, check the box next to Cognito User Pool.
xvii) Next, construct the Callback URL list. Replace the placeholder value <VID> in following URLs with your developer account’s Vendor ID. To find your vendor ID, go to https://developer.amazon.com/settings/console/mycid and sign in with your Amazon Developer account if prompted.
https://alexa.amazon.co.jp/api/skill/link/<VID>https://layla.amazon.com/api/skill/link/<VID>https://pitangui.amazon.com/api/skill/link/<VID>
Note that these three URLs correspond to the three Alexa regions: FE (co.jp), EU (layla), NA (pitangui).
Combine them into a single comma-seperated value and Copy/paste the comma-separated Callback URL list into the Callback URL(s) field.
xvii) Under OAuth 2.0 and Allowed OAuth Flows, check the box as Authorization code grant. Under Allowed OAuth Scopes, check these boxes:
openid, aws.cognito.signin.user.admin, profile
Openid- Returns all user attributes in the ID token that are readable by the client.
aws.cognito.signin.user.admin- Grants access to Amazon Cognito User Pool API operations that require access tokens.
profile- Grants access to all user attributes that are readable by the client.
Click Save changes.
There are two options for setting the Cognito OAuth domain.
I. Use a Cognito Domain: This option can only be used for trial and demonstration purposes.
II. Use Your Own Domain: This option is required if a developer intend to publish a skill that makes use of the Cognito pool.
Since, I’m doing this example for just try and out, I will continue using a Cognito domain.
i) Select App integration > Domain name from the left-side menu.
ii) Chose a domain prefix and enter it into the Domain Prefix field.
iii) Click Check availability. It will be prompted whether the domain prefix is already existing or not.
iv) Once you have received an available domain prefix, click Save changes.
v) Select App integration from the left-side menu. You can see the full URL as ( https://chathurangis-userportal.auth.us-east-1. amazoncognito. com) in the Domain field.
If an Alexa developer have a domain managed by Amazon Route 53, the they can choose this option.
In this section, we can create an AWS IAM Role (with policy) which will be used by the Lambda function that backs your skill.
Navigate to the AWS IAM Console.Click Policies on the left-side menu.Click the Create Policy button.Create a policy as per your requirement.Select Roles on the left-side menu and Click the Create role button.Under Select type of trusted entity, select AWS service.Under Choose the service that will use this role, select Lambda.Click the Next:Permissions button.Search the policy you created earlier and check the box next to your policy.Click the Next:Tags button, then the Next:Review button.Enter a suitable name and click the Create role button.
Navigate to the AWS IAM Console.
Click Policies on the left-side menu.
Click the Create Policy button.
Create a policy as per your requirement.
Select Roles on the left-side menu and Click the Create role button.
Under Select type of trusted entity, select AWS service.
Under Choose the service that will use this role, select Lambda.
Click the Next:Permissions button.
Search the policy you created earlier and check the box next to your policy.
Click the Next:Tags button, then the Next:Review button.
Enter a suitable name and click the Create role button.
You can create your own Alexa skill using Alexa Skills Kit developer console through your Amazon Developer account:
Create an AWS Lambda function. You can use either creating lambda function from scratch or use an existing template or deploy a sample lambda application from AWS Serverless Application Repository.
Copy the ARN of the lambda function you created from the Amazon console.
Copy the ARN of the lambda function you created from the Amazon console.
2. Now ,Navigate to the Endpoint section in Alexa Developer Console, click AWS Lambda ARN and enter the copied ARN under Default Region.
In the Alexa developer console, Select ACCOUNT LINKING on the left-side menu.Make the following options “ON”.
In the Alexa developer console, Select ACCOUNT LINKING on the left-side menu.
Make the following options “ON”.
3. Next, Under Security Provider Information, enter following configs.
i) Set Auth Code Grant as Authorization Grant Type.
ii) Set Authorization URI, by replacing <example_domain> with your domain and <VID> with your in vendor ID the following URL: https://<example_domain>/oauth2/authorize?redirect_url=https://pitangui.amazon.com/api/skill/link/<VID>
iii) Set Access Token URI, by replacing <your_domain> with your domain in the following URL: https://<example_domain>/oauth2/token
iv) Set Client ID and Client Secret, by the corresponding values you found on Cognito.
v) Leave Client Authentication Scheme as HTTP Basic (Recommended).
vi) Click + Add scope and enter openid, + Add scope and enter profile and k + Add scope and enter aws.cognito.signin.user.admin.
vii) Click + Add domain and enter your domain name. Note that here Domain List value should be entered excluding https://.
viii) That’s All . Click the Save button.
Now, you can test the skill by Beta Testing or by logging in to the Alexa website for your region.
I - Alexa Beta Testing
To carry a Beta Test, Go to Distribution section in Alexa Developer Console.Complete the Store Preview, Privacy & Compliance and Availability sections with your respective details.Then, under Availability, you will be informed whether your skill is ready for Beta Test.
To carry a Beta Test, Go to Distribution section in Alexa Developer Console.
Complete the Store Preview, Privacy & Compliance and Availability sections with your respective details.
Then, under Availability, you will be informed whether your skill is ready for Beta Test.
In the same, you can add an Administrator and Testers as per need for the Beta Test.
II- Testing via Amazon
Log in to the Alexa website (alexa.amazon.com) using the same amazon developer account in which you have created the skill.Navigate to the skill’s detail page. Click on Skills. Click Your Skills.Click on the DEV SKILLS tab and find your alexa skill and click on it.
Log in to the Alexa website (alexa.amazon.com) using the same amazon developer account in which you have created the skill.
Navigate to the skill’s detail page. Click on Skills. Click Your Skills.Click on the DEV SKILLS tab and find your alexa skill and click on it.
In either of the above two ways, you can access your skill in Test mode. Next you will be prompted to Enable your skill. If already enabled, click Settings and then click Link Account.
3. Next, a new browser tab will open. Create the user by Clicking Sign up. Fill the details. Recall that they are the variables that you initiated when creating the User pool. Next Click Sign up.
4. Next a window will prompted asking a verification code. Enter the verification code you received by email and click Verify. Now your user has been added to the user pool. You can view the added user by navigating to Users and groups in General settings under Cognito Federated Identities.
5. Then, Again click Sign-In and enter the email and password for the account you just entered. If the authentication succeeded, your skill and account are now linked. You will get following success tab.
Go back to the Amazon developer console and navigate to Test tab. Test out your skill using the utterances you specified when creating the skill. Following is a snapshot of my skill when it is authenticated and linked with my account. You can see the request and the succeeded response in the JSON editor. Alexa simulator will display the personalized result.
We have now successfully linked the skill with the user account.
The same process can be followed if you are going to another most used verification mechanism like Mobile OTP. The only modification you have to do is in Cognito user pool set Email address or phone­­­­­ numbers and choose Allow phone numbers. And then, select phone_number in standard attribute list.
Even though, there are SMS pricing restrictions and limitations as per regions in using Mobile OTP. However, no such restrictions do apply for Email based verification.
Hope you got a clear understanding on how Alexa Account Linking works through this blog post. If you have any issues or comments on this blog post please leave a comment below.
Cheers and Happy Learning!