Discover how to use account linking with Login with Amazon to seamlessly integrate your Alexa skills with third-party application. Get step-by-step instructions from Sebastien Stormacq, Sr. Solutions Architect at Amazon.
Some skills require the ability to connect the identity of an Alexa end user with a user in another system, such as Twitter, Facebook, Amazon, and many others. For example, suppose you own a web-based service “Car-Fu” that lets users order taxis. It would be very convenient for people to access Car-Fu by voice (“Alexa, ask Car-Fu to order a taxi”).
To accomplish that, you’d use a process called account linking, which provides a secure way for Alexa skills to connect with third-party systems requiring authentication.
Skills that use the Smart Home Skill API must use account linking (with the authorization code grant flow) to connect the Alexa user with their device cloud account. Custom skills can use account linking if desired. However, if your custom skill merely needs to keep track of a user to save attributes between sessions, you do not need to use account linking.
There are many ways you can use account linking to enhance your Alexa skills. For example:
Account linking leverages OAuth 2.0; an open protocol that provides a simple, standards-based method for web, mobile and desktop applications to request user authorization from remote servers.
As a skill developer, you could set up and configure your own OAuth server and identity management system. At some large companies, an OAuth server is probably already available and Identity Management procedures already in place. However, at smaller companies, this would require you to build, operate, and maintain your own complex system to manage user identities, passwords, and profiles in a secure and scalable way.
Many organizations rely instead on well-known identity providers, available on the internet. These are sites where nearly everyone has an account, such as Facebook, Google, Twitter, and Amazon. The service that acts as a public-facing identity provider for Amazon is Login with Amazon.
When using OAuth, you delegate user authentication to a third-party Identity Provider (IDP). As illustrated below, the user is redirected to the IDP web site. User authentication happens according to the IDP’s policies (username and password, one-time password, biometric, etc.), and upon successful authentication, the IDP generates an implicit grant (aka bearer token) or an authorization code grant.
The bearer token is the token you'll use for accessing information and services. On the other hand, an authorization code can only be used to request a bearer token. This usually happens on the backend, between your application server and the IDP service. While an implicit grant is often faster and simpler for developers to request, an authorization code grant is generally considered more secure and some IDPs may require it for sensitive information or services. Also, a code grant allows for automatic refreshing of the bearer token after a given expiry, which will be set according to the IDP’s policy. When using an implicit grant, the user has to manually re-authenticate themselves when attempting to use the service, which, depending on the lifespan of the bearer token, can cause friction for account linking in applications.
After authentication is complete and a valid token is received, your application is responsible for managing authorization based on the customer's profile.
Figure 1 : OAuth data flow
Follow these steps to configure your Alexa skills with account linking and Login with Amazon.
If you haven’t created a skill yet, please first use the Alexa Skills Kit to build something relatively simple, such as a trivia skill. You can get a prototype up and running in just a few hours and come back here once it’s published.
First, you need to create a LWA profile for your Alexa skill. Here’s how.
Figure 2 : Access Login With Amazon
Fill in all three required fields to create your security profile and click “Save”. For the purpose of this article, I am using Amazon’s privacy policy URL. Make sure to replace the link with a link to your own Data Privacy policy.
Figure 3 : Create Security Profile
Before you complete this step, be sure to copy your Client ID and Client Secret (see Figure 4) to a text editor so they're easily available. You’ll need these values later in the process.
Figure 4 : Collect Client ID and Client Secret
Now that you’ve configured Login with Amazon, you can configure Account Linking for your Alexa skill. (Remember, you need to have a skill already created to do this).
In the Alexa developer console, you might see a 'get started' button for Alexa skills even if you have a skill in development. Press it, then "edit" the skill to get to the configuration screen.
Under the “Configuration” tab for your skill, enable “Account Linking” if it is disabled. Then, enter the following:
Figure 5 : Account Linking Details
The values you need to enter into these fields are detailed in the table below.
Key |
Value |
Account Linking |
Yes |
Authorization URL |
https://www.amazon.com/ap/oa |
Client ID |
The Client ID received from Login with Amazon during Step 1 above. This has a format such as amzn1-application-oa2-client-xxx |
Scope |
Login with Amazon supports several scopes, for this example, let’s use “profile”. This will allow your code to retrieve a unique Amazon userid, email address, and full name for the user. |
Authorization Grant Type |
Select “Auth Code Grant” |
Access Token URI |
This is the URI the Alexa Service needs to use to exchange an authorization code for a token and to refresh expired tokens. This is the same value for all Login with Amazon applications : https://api.amazon.com/auth/o2/token |
Client Secret |
The client secret received from Login With Amazon during Step 1 above. |
The Authorization URL is the Amazon Login URL (https://www.amazon.com/ap/oa).
The Redirect URL parameter tells Login with Amazon where to redirect the browser after an authentication. In our case, it is the URL provided by the Alexa Skills Kit (ASK) console, labeled “Redirect URL”, and starting with https://pitangui.amazon.com/api/skill/link…
Figure 6 : ASK Redirect URI
The last step is to configure Login with Amazon to accept our redirection URL. The redirection is URL is given on the Alexa Developer Console, under “Redirect URL”. This is the URL starting by https://pitangui.amazon.com/api/skill/link/…
Copy this value to that text editor I suggested earlier and go back to the Login with Amazon console.
Next to the Security Profile you created in Step 1, click the button with the gear icon and select “Web Settings” from the menu.
Figure 7 : Login with Amazon - Web Settings
Click the "Edit" button in the lower right, then enter the Redirect URL, as it appears on the ASK Developer Console.
Figure 8 : Login with Amazon - Redirect URL
Now you are ready to write some code.
For the purpose of this blog post, I chose to write the Alexa custom skill code in NodeJS and deploy it on AWS Lambda.
You can learn more about writing code for custom skills here and here.
When your skill is called the first time, you will receive a JSON document like this:
{ "session": { "sessionId": "SessionId.7c77f955-ae5e-46f1-a9ca-3fb354b1ce77", "application": { "applicationId": "amzn1.echo-sdk-ams.app.fb2fc3e7-55e7-4f05-851e-7ad308a6b499" }, "user": { "userId": "amzn1.ask.account.AFP3ZWPOS2BGJR7OWJZ3DHPKMOMNWY4AY66FUR7ILBWAN IHQN73QHMAHCTVTAHFPUV3WAFNGKBYW5LFUE2WV4CCGEISSPHBHCW5SCYJDL3DLWRRRBB4CQIP3X3PV6 5V2AYMMXSNFPKHPZJFVAH5AHKHDLAER67H3AHL4XBUU76XEH5BGDZZNGV5T6HHAGN6KGZI777J3VA7WGPA" }, "new": true }, "request": { "type": "IntentRequest", "requestId": "EdwRequestId.b595d667-caa3-4818-8d4a-c7a31e8adddc", "timestamp": "2016-05-27T15:36:26Z", "intent": { "name": "SayHello", "slots": {} }, "locale": "en-US" }, "version": "1.0" }
Notice that the “user” section contains a userId properties, but no OAuth access token yet as we did not authenticate our user yet.
Whenever your code receives such input, it should return a “LinkAccount” card, displayed in the Alexa app or the Alexa web site. The card will contain a link allowing the user to authenticate on Login with Amazon. In addition to the card, it is a recommended practice to return a voice prompt inviting the user to authenticate in the app.
The NodeJS code to generate such an answer might be like:
//if no amazon token, return a LinkAccount card if (alexa.event.session.user.accessToken == undefined) { alexa.emit(':tellWithLinkAccountCard', 'to start using this skill, please use the companion app to authenticate on Amazon'); return; }
and the corresponding JSON output looks like this:
{ "version": "1.0", "response": { "outputSpeech": { "type": "PlainText", "text": " Please use the companion app to authenticate on Amazon to start using this skill" }, "card": { "type": "LinkAccount" }, "shouldEndSession": false }, "sessionAttributes": {} }
When you invoke your skill from a device, you will receive a card in the Alexa app asking you to link your account.
Figure 9 : Account Linking Card
Click on the “Link Account” link, and the Login with Amazon page will display.
Figure 10 : Login with Amazon Credentials
Authenticate using your regular Amazon login (the same login used when shopping on Amazon.com).
The very first time, Amazon will ask you if you authorize the Alexa skill to retrieve some data from your user profile.
Figure 11 : Login with Amazon - Authorization Screen
Click ‘Okay’ and a confirmation message appears.
Figure 12 : Success - Account Linking is complete
Invoke the skill again. Now, because your account is linked, an Amazon OAuth Token is included in the input JSON document.
{ "session": { "sessionId": "SessionId.7fc6aa11-8a2c-4f3f-a1ea-001569cd0035", "application": { "applicationId": "amzn1.echo-sdk-ams.app.fb2fc3e7-55e7-4f05-851e-7ad308a6b499" }, "user": { "userId": "amzn1.ask.account.AFP3ZWPOS2BGJR7OWJZ3DHPKMOMNWY4AY66FUR7ILBWANIHQN73 QHMAHCTVTAHFPUV3WAFNGKBYW5LFUE2WV4CCGEISSPHBHCW5SCYJDL3DLWRRRBB4CQIP3X3PV65V2AYMMX SNFPKHPZJFVAH5AHKHDLAER67H3AHL4XBUU76XEH5BGDZZNGV5T6HHAGN6KGZI777J3VA7WGPA", "accessToken": "Atza|IQEBLjAsAhRBk1-yYVTk9HhZEQnTGL9F3RHS5gIUG0rrerkVvpVTF5k IFWBvZIx7QtJCkzsRFRf1ZAIZeRz6FJwdeyQCLPEbqLnEKU-zQF4n9x76Dl24Rt7HiltefBilnDm0c2PZQP _IUBAzcm93CIDxsMYhEmW_Pr0Tm9tIrGzNzVntLgyiUeXmasL1bUOIv_om66ZVwd7urpyiJSoSbA-1NQ 7O9AKC2qXMqvFpvFUBSvgCYoTyyAkOePN63FCaq9NJPYbJLuocqcuyGz9mygNqp9_mNRWRRzcoeSTx pUoa8LxW-IvVVFEA1omCfXmcVijEZA6nbi-EzheMG7fu1y0XNGPEy40Csq7H07wrSqksz9IDIUd4t mqiYsJpN4dxfoGddEauC3i4eLCvsg8gbu963CqqUQ3COxgrWKTsqX8AsT8FCFvmfW3IYfhCG6KuPw8 qntBgAU-W9pW523lERQKLxzI07UHyMd2R-Fnaw8IWbBYFCbblwIJhf6twjz9z_4h320f4ywczBa3k_ LCoE0VpidER7rVgBtfreox-XYqV5jw" }, "new": true }, "request": { "type": "IntentRequest", "requestId": "EdwRequestId.31777921-9438-44f7-b271-6b9808d5fba9", "timestamp": "2016-05-27T16:18:57Z", "intent": { "name": "SayHello", "slots": {} }, "locale": "en-US" }, "version": "1.0" }
Your code can use this access token to fetch the user profile data from the Amazon Profile service API.
var request = require('request'); var amznProfileURL = 'https://api.amazon.com/user/profile?access_token='; amznProfileURL += session.user.accessToken; request(amznProfileURL, function(error, response, body) { if (response.statusCode == 200) { var profile = JSON.parse(body); alexa.emit(':tell', "Hello, " + profile.name.split(" ")[0]); } else { alexa.emit(':tell', "Hello, I can't connect to Amazon Profile Service right now, try again later"); } });
The code above will return the following JSON output:
{ "version": "1.0", "response": { "outputSpeech": { "type": "PlainText", "text": "Hello, Sebastien" }, "shouldEndSession": true }, "sessionAttributes": {} }
Notice the first name, taken out of the Amazon profile.
Congratulations, if you coded along to this point, you have successfully implemented Account Linking with the Login with Amazon service.
Tell us how you’re enhancing your Alexa skills using account linking by tweeting us @AlexaDevs. For further info, check out our developer pages on Account Linking and how to use the Login with Amazon service.