アクセスいただきありがとうございます。こちらのページは現在英語のみのご用意となっております。順次日本語化を進めてまいりますので、ご理解のほどよろしくお願いいたします。お問い合わせは「サポート」タブの「お問い合わせ」からご連絡ください。

Link an Alexa User with a User in Your System

Overview

Some skills require the ability to connect the identity of the end user with a user in another system. This is referred to as account linking, since the goal is to create a link between the Alexa user and the user account in your system. 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 accounting linking if needed.

For example, suppose you own a web-based service “Car-Fu” that lets users order taxis. A custom skill that lets users access Car-Fu by voice (“Alexa, ask Car-Fu to order a taxi”) would be very useful. Completing this request requires the skill to access your Car-Fu service as a specific Car-Fu user. Therefore, you need a link between the Amazon account used with the Alexa device and the Car-Fu account for the user.

This document describes the supported methods for establishing this type of link between an Alexa user and a user in your system.

Note that account linking is needed when the skill needs to connect with a system that requires authentication. If your custom skill just needs to keep track of a user to save attributes between sessions, you do not need to use account linking. Instead, you can use the userId provided in each request to identify the user. The userId for a given user is generated when the user enables your skill in the Alexa app. Every subsequent request from that user to your skill contains the same userId unless the user disables the skill.

How Account Linking Works

To connect an Alexa user with an account in your system, you need to provide an access token that uniquely identifies the user within your system. The Alexa service stores this token and includes it in requests sent to your skill’s service. Your skill can then use the token to authenticate with your system on behalf of the user.

Using account linking in the Alexa Skills Kit assumes some familiarity with the OAuth 2.0 authorization framework. Two OAuth authorization grant types are supported:

The primary difference between these two types is in how the access token is obtained from your system. From the end user’s perspective, there is no difference.

OAuth Roles and the Alexa Skills Kit

OAuth 2.0 specifies four roles: resource owner, resource server, client, and authorization server. When using OAuth with the Alexa Skills Kit, these roles are defined as follows:

  • Resource owner: the end user who wants to connect your skill with their user account in your system.
  • Resource server: The server hosting the resources the user wants to access. This server is part of your system, and it must be able to accept and respond to requests using access tokens. In the Car-Fu example, this is part of the Car-Fu service. The protected resource is the user’s Car-Fu account profile.
  • Client: The application making the requests to the resource server on behalf of the resource owner. In this context, this is the Alexa service.
  • Authorization server: The server that authenticates the identity of the resource owner and issues access tokens. In the Car-Fu example, this is also part of the overall Car-Fu service.

Note that the resource server and authorization server can be the same server.

How End Users Set Up Account Linking for a Skill

Users link their accounts using the Amazon Alexa app. Note that users must use the app. There is no support for establishing the link solely by voice. Users can start the process:

  • When initially enabling your skill in the app
  • After making a request that requires authentication. In this case, your skill returns a LinkAccount card, and the user can start the process from the card in the Alexa app. Note that this scenario is possible for custom skills, but not smart home skills.

The specific flow varies depending on whether you are using implicit grant or authorization code grant, but the end-user steps are the same for both.

Account linking flow for authorization code grant (for use with smart home skills or custom skills):

  1. In the Alexa app, the user enables the skill.
  2. The app displays your login page right within the app, using the Authorization URL you provide when registering your skill on the developer portal. When the companion app calls this URL, it includes state, client_id, response_type, scope, and redirect_uri as query string parameters.
    • The state is used by the Alexa service during the account linking process. Your page needs to keep track of this value, as you must pass it back later.
    • The client_id is a value defined by you when you set up account linking for the skill in the developer portal.
    • The response_type is always code for the code grant flow.
    • The scope is an optional list of access scopes indicating the level of access requested. You define the set of scopes to support when enabling account linking for your skill.
    • The redirect_uri is the URL to which your service redirects the user once the user is authenticated.
  3. The user logs in using their normal credentials for your site.
  4. Your service authenticates the user and then generates a code.
  5. Your service redirects the user to the specified redirect_uri and passes along the state and code in the URL query parameters.
  6. The Alexa service validates the returned information, then uses the code to request an access token and refresh token pair from your authorization server (specified in the Access Token URI field in the developer portal). Both of these items are saved for the Alexa user.
  7. The user’s Alexa account is now linked to the account in your service, and the skill is ready to be used.

Account linking flow for implicit grant (for use with custom skills):

  1. In the Alexa app, the user enables the skill.
  2. The app displays your login page right within the app, using the Authorization URL you provide when registering your skill on the developer portal. When the companion app calls this URL, it includes state, client_id, response_type, and scope as query string parameters.
    • The state is used by the Alexa service during the account linking process. Your page needs to keep track of this value, as you must pass it back later.
    • The client_id is a value defined by you when you set up account linking for the skill in the developer portal.
    • The response_type is always token for the implicit grant flow.
    • The scope is an optional list of access scopes indicating the level of access requested. You define the set of scopes to support when enabling account linking for your skill.
    • The redirect_uri is the URL to which your service redirects the user once the user is authenticated.
  3. The user logs in using their normal credentials for your site.
  4. Your service authenticates the user and then generates an access token that uniquely identifies the user in your system.
  5. Your service redirects the user to the specified redirect_uri and passes along the state, access_token, and token_type in the URL fragment.
  6. The Alexa service validates the returned information and then saves the access_token for the Alexa user.
  7. The user’s Alexa account is now linked to the account in your service, and the skill is ready to be used.

What Happens when a User Invokes a Skill with Account Linking

When a user begins interacting with a custom skill that has been set up with account linking, the following occurs:

  1. The user invokes the skill normally. For example: “Alexa, ask Car-Fu to order me a taxi.”
  2. If using authorization code grant, the Alexa service makes sure that the access token saved for the user is still valid. If it has expired, the Alexa service uses the refresh token to request a new access token from your authorization server.
  3. The LaunchRequest or IntentRequest sent to the service for your skill includes the previously-saved access token for the user.
  4. Your service validates that the token matches a user in your system:

    • If the token is valid for a user, your service accesses the user’s information as needed, completes the request normally, then sends back an appropriate response with the text to speak to the user and the optional card to display in the Alexa app.

      For instance, in the Car-Fu example, the Car-Fu skill verifies that the provided token matches a valid Car-Fu user. If it does, the service can access the Car-Fu profile for that user and use that information to complete the user’s request for a car.

    • If the token is invalid, your service returns text telling the user to link their account and a LinkAccount card. The user can click the link on this card to start the account linking process:

      Example of a LinkAccount card
      Example of a LinkAccount card

The process is similar for smart home skills:

  1. The user invokes the skill normally. For example: “Alexa, turn on the living room lights.”
  2. The Alexa service makes sure that the access token saved for the user is still valid. If it has expired, the Alexa service uses the refresh token to request a new access token from your authorization server.
  3. The device directive sent to your skill adapter includes the previously-saved access token in the payload.
  4. Your skill adapter passes along the token to the device cloud to complete the user’s request.
    • If the token is valid, the device cloud completes the request normally and turns on the requested light.
    • If the token is invalid, your skill adapter should return a DependentServiceUnavailableError. Alexa then tells the user that she was unable to complete the request.

For more about device directives, see the Smart Home Skill API Reference.

What Happens if the User Disables a Skill with Account Linking

If the user disables the skill in the Alexa app, the Alexa service deletes the access token (and refresh token if applicable) associated with that user and skill. This essentially removes the link between the user’s Alexa account and their account in your service.

If the user later re-enables the skill, they will need to complete the account linking process as a new user.

What Do You Need to Add Account Linking to Your Skill?

To implement account linking in a skill, you need the following:

Authorization Code Grant Implicit Grant
A web-based service that authenticates users. A web-based service that authenticates users.
An authorization server that can present a login page to collect user’s credentials, authorize the user, and then generate an authorization code. An authorization server that can present a login page to collect user’s credentials, authorize the user, and then generate an access token that uniquely identifies that user.
An authorization server that can accept the authorization code and Alexa’s client credentials and generate an access token that uniquely identifies that user. Not Applicable

To add account linking to your skill, you must do the following:

  1. Add account linking support to the login page for your service.
  2. Add account linking logic to the cloud-based service (web service or Lambda function) for your skill.
  3. Enable account linking for your skill on the developer portal.

See the sections below for details about these steps.

Adding Account Linking Support to Your Login Page (Authorization URL)

When a user starts the process of linking accounts, the Alexa app displays a login page for your resource server. You need to design and code a page appropriate for this purpose. The page needs to validate the user’s credentials and then return either an access token or authorization code.

You provide the URL for this page in the Authorization URL field when enabling account linking for your skill in the developer portal.

Providing the Login Page in the User’s Language

The Alexa app attempts to use the user’s browser language preference to display a localized version of the app if the user’s browser is set to one of the supported languages (en-us, en-gb, or de-de). For other languages, the app defaults to en-us.

For a consistent user experience, your login page should also render in the same language as the Alexa app. To get the language, check the Accept-Language header first. The Alexa app attempts to set this when calling your Authorization URL.

If the header is not set, you can use the language defined by the user’s browser by checking navigator.language or navigator.browserLanguage. See Navigator language Property.

Note that the user’s browser settings are independent of the language defined on the user’s Alexa-enabled device. For example, a user could configure their device to use German, but configure their browser to use UK English. In this case, the Alexa app renders in English and the Accept-Language header is set to English (en-gb).

Parameters Passed to Your Authorization URL

The Alexa app includes the following parameters in the URL query string when it calls your Authorization URL:

  • state is used internally by the Alexa service to track the account linking process.

    Your page must pass this value back (unchanged) when calling the redirect URL.

  • client_id is an identifier defined by you. You can use this to provide any skill-specific functionality, such as distinguishing between different skills you have configured with account linking. You define your client_id when enabling account linking for your skill in the developer portal.
  • The response_type value depends on whether you are using authorization code grant or implicit grant.
    • code for authorization code grant.
    • token for implicit grant.
  • scope is an optional list of scopes indicating the access the Alexa user needs. You define these scopes when enabling account linking for your skill in the developer portal.
    • You can use this information when generating the access token. For example, you could create a token that allows access to basic profile information in your resource server, but does not allow access to payment information.
    • Multiple scopes can be used. The list is delimited by URL-encoded spaces.
    • You may want to also tell users what access they are allowing by linking their accounts. For instance, your login page could display text such as “This allows the Car-Fu skill to order a taxi on your behalf and charge your account for the cost.”
  • redirect_uri is the Amazon-specific redirect URL (OAuth Redirection Endpoint) to which your service should redirect the user after authenticating the user. The values you can expect for this parameter are also displayed on the developer portal when you configure account linking, so you can verify that the URL is valid.

For example, if the authorization URL for your page is https://www.carfu.com/login, the URL called by the Alexa app might look like this (for authorization code grant):

https://www.carfu.com/login?state=abc&client_id=alexa-skill&scope=order_car%20basic_profile&response_type=code&redirect_uri=https%3A%2F%2Fpitangui.amazon.com%2Fspa%2Fskill%2Faccount-linking-status.html%3FvendorId%3DAAAAAAAAAAAAAA

Requirements for Your Login Page

Your login page should meet the following requirements:

  • It must be served over HTTPS.
  • It must be mobile-friendly, as it will be displayed within the Alexa app.
  • The page cannot open any pop-up windows.
  • It must accept the user’s credentials and then authenticate the user.
  • It must either:
    • Generate an access token that uniquely identifies the user to your resource server.
    • Generate an authorization code that can be passed to your authorization server to retrieve an access token.
  • It must keep track of the state value passed in the query string.
  • After authenticating the user, the page must redirect the user to one of two Amazon-provided redirect URLs.
    • The redirect URL you use is included in the authorization request as the redirect_uri parameter.
    • Two redirect URLs are also displayed in the developer portal when you turn on the account linking options for your skill, so you can see the possible values your login page should expect in the redirect_uri parameter.
    • For authorization code grant, include the state, and code in the URL query string.
    • For implicit grant, include the state, access_token, and token_type in the URL fragment. The token_type should be Bearer.

For example, assume your Amazon-provided redirect URL is the following:

https://pitangui.amazon.com/spa/skill/account-linking-status.html?vendorId=AAAAAAAAAAAAAA 

For authorization code grant, the redirect URL might look like this:

https://pitangui.amazon.com/spa/skill/account-linking-status.html?vendorId=AAAAAAAAAAAAAA&state=xyz&code=SplxlOBeZQQYbYS6WxSbIA 

The parameters you must pass back (state and code) are in the query string portion of the URL.

For implicit grant, the redirect URL might look like this:

https://pitangui.amazon.com/spa/skill/account-linking-status.html?vendorId=AAAAAAAAAAAAAA#state=xyz&access_token=2YotnFZFEjr1zCsicMWpAA&token_type=Bearer

The parameters you must pass back (state, access_token, and token_type) are in the URL fragment portion of the URL. This is the portion after the hashtag (#).

About Access and Refresh Tokens

Your authorization server needs to provide an access token that uniquely identifies a user in your system.

For authorization code grant, the Alexa service calls your authorization server (specified as the Access Token URI in the developer portal) and passes the code and client credentials. The authorization server must return the access token and an optional refresh token. Although the refresh token is optional, it is recommended if your access token expires. The Alexa service can use the refresh token to get a new access token when the previous one expires, without disrupting the end user.

For implicit grant, your login page includes the access token when calling the redirect URL, as shown in the redirect URI examples above. Implicit grant does not support refresh tokens, so if the token expires, the end user will need to re-link the accounts. If you want to use expiring tokens, use authorization code grant instead.

For either type, when generating the access token, provide a token specific to your resource server. Do not use access tokens provided by other OAuth providers such as Google or Facebook. For security, your token should be a value that identifies the user, but cannot be guessed.

Adding Account Linking Logic to the Service for Your Skill

To add account linking to your skill, you need to code the logic to verify and use the access token included in requests sent to your skill.

Getting the Access Token from the Request (Custom Skills)

When using the Java library, the access token is available in the Session object passed to the onIntent(), onLaunch(), and onSessionEnded() methods. You can use the Session.getUser() method to retrieve a User, then call User.getAccessToken() to get the token.

In the JSON, the access token is available in the accessToken property of the user object in the request:

{
  "version": "string",
  "session": {
    "new": boolean,
    "sessionId": "string",
    "application": {
      "applicationId": "string"
    },
    "attributes": {
      "string": object
    },
    "user": {
      "userId": "string",
      "accessToken": "string"
    }
  },
  "request": object
}

Getting the Access Token from the Request (Smart Home Skills)

The access token is sent to your skill adapter as part of the device directive, in the accessToken property of the payload object.

For example, note this DiscoverAppliancesRequest directive:

{
  "header": {
    "namespace": "Alexa.ConnectedHome.Discovery",
    "name": "DiscoverAppliancesRequest",
    "payloadVersion": "2",
    "messageId": "6d6d6e14-8aee-473e-8c24-0d31ff9c17a2"
  },
  "payload": {
    "accessToken": "string"
  }
}

Validating the Access Token

For a request that requires authentication, your code should do at least two checks:

  1. Validate that the accessToken exists (custom skills only).

    In the Java library, User.getAccessToken() returns null if the user has not successfully linked their account.

    In the JSON, the accessToken property does not exist if the user has not linked their account.

    Note that this check does not apply to smart home skills. It is not possible to enable a smart home skill without also successfully linking the accounts.

  2. If the accessToken exists, verify that it is valid and identifies a user in your resource server. An existing token could become invalid for multiple reasons, for example:

    • The user deleted or canceled their account with your service. For example, an Alexa user might have set up account linking with Car-Fu, then later canceled their Car-Fu account. At this point, the token stored by the Alexa service would identify a non-existent user.
    • The token has expired, and the Alexa service was unable to obtain a new token. This can occur when using authorization code grant if your authorization server does not provide refresh tokens. This can also occur if you are using the implicit grant authorization, which does not support refresh tokens.

If the token is valid, the skill can handle the request normally, accessing data from your resource server as needed. In the Car-Fu example, the skill would retrieve profile and payment information for the user from the Car-Fu service, order a car, and return a confirmation to the user. See the “Returning a Response” section of Handling Requests Sent by Alexa for more about returning responses.

Responding to an Invalid Access Token (Smart Home Skills)

If the access token sent to your skill adapter for a smart home skill is invalid, return a DependentServiceUnavailableError. Alexa then tells the user that she was unable to complete the request.

Responding to an Invalid or Non-existent Access Token (Custom Skills)

If the access token sent to your custom skill does not exist or is invalid, your skill should return a response containing the following:

  • Output speech text explaining to the user that they need to link their account to use this feature.
  • A link account card. This is a special type of card that tells the user to link their account. When displayed in the Alexa app, this card displays a link to the URL for your login page. The user can start the account linking process right from this card.

To send the link account card:

  • When using the Java library, create an instance of the LinkAccountCard class and include it as the card in your response.
  • When using JSON, set the card type to LinkAccount:

     {
         "version": "1.0",
         "sessionAttributes": {
           ...(session attributes not shown)
         },
         "response": {
           "outputSpeech": {
             "type": "PlainText",
             "text": "You must have a Car-Fu account to use this skill. Please use the Alexa app to link your Amazon account with your Car-Fu Account."
           },
           "card": {
             "type": "LinkAccount"
           },
           "shouldEndSession": true
         }
     }
    

In most cases, this response should end the session, since the user cannot continue with their request until after they have linked their account. If your skill includes some intents that don’t require authentication, it may make sense to ask the user a different question and keep the session open.

When to Require a Valid Access Token

Your service should validate the accessToken for every request that requires the user to authenticate with your web site.

For a smart home skill, this includes every directive.

For a custom skill, this usually includes most intents, but you can have intents that don’t require authentication. For example, the Car-Fu custom skill might require user authentication to order a car, but does not require authentication to just ask whether the service is available in a particular city. Therefore, the code for this skill might do the following:

  • The handler for an OrderTaxi intent would check for a valid accessToken and use that token to retrieve the user’s Car-Fu profile and order a car.
  • The handler for a generic TaxiAvailabilityByCity intent would not need to check for an accessToken, but would look up public information on the Car-Fu service and return a response.

Enabling Account Linking for a Skill in the Developer Portal

You enable account linking on the Configuration page in the Amazon Developer Portal.

After registering your skill on the portal normally, navigate to the Configuration page and select Yes for Account Linking or Creation. Note that this option is not displayed for smart home skills, since account linking is always required.

At a minimum, you must enter the following to enable account linking:

  • Authorization URL: The URL for your web site’s login page. Refer back to Adding Account Linking Support to Your Login Page for information about how this page is used when users link their accounts.
  • Client Id: An identifier your login page uses to recognize that the request came from your skill. This value is passed to your authorization URL in the client_id parameter. When using authorization code grant, this value is also part of the client credentials that the Alexa service includes when requesting an access token from the Access Token URI.
  • Authorization Grant Type: The type of OAuth 2.0 authorization grant to use to obtain the access token. The Alexa Skills Kit supports two grant types:
  • For Authorization Code Grant, you must also fill in the following:
    • Access Token URI: The URL for the authorization server that provides the access tokens.
    • Client Secret: A credential you provide that lets the Alexa service authenticate with the Access Token URI. This is combined with the Client Id to identify the request as coming from Alexa.
    • Client Authentication Scheme identifies the type of authentication Alexa should use when requesting tokens from the Access Token URI.
  • Privacy Policy URL: A URL for a page with your privacy policy. This link is displayed in the Alexa app. This is required for skills that use account linking. Note that the URL you enter is also shown in the Privacy Policy URL field on the Privacy & Compliance page.

If your login page retrieves content from other domains, enter those in the Domain List. This is only necessary for domains beyond your authorization URL. For example, suppose your authorization URL is https://www.carfu.com/login. If your page pulls in any content (such as images) from domains other than www.carfu.com, you would add them to the Domain List.

If your resource server supports different scopes for access, enter those in the Scope list. All of the scopes entered here are included in the scope parameter when the Alexa app calls your authorization URL.

Redirect URL Values

Enabling account linking displays your Redirect URL. This is the URL to which your login page must redirect the user after they are authenticated. This value is also passed to your login page as the redirect_uri parameter included with the Authorization URL.

Note that there are multiple Redirect URL values. The Alexa app passes your Authorization URL the value you should use based on where the user registered their device.

The parameters your page needs to include when redirecting the user after authentication depend on the whether you are using authorization code grant or implicit grant. Refer back to Requirements for Your Login Page.

Next Steps

Coding topics (custom skills):

Other topics:

Reference materials: