In part 3 of this series, we describe how a Skill using account linking can get an access token in the Skill Service. Havin the access token is a prerequisite for calling an API.

First, if no access token is present, the Alexa Skill needs to log the user in on the authorization endpoint. This process is only available via GUI, so the voice Skill needs to direct the user to the screen of the device or of the Alexa App. The important part is the withLinkAccountCard() function, that calls the authorization URL specified in the Skill Interface configuration.

const Handler = {
handle(handlerInput) {
// get the access token from the context
var accessToken = handlerInput.
requestEnvelope.context.System.user.accessToken;
// no access token? need to trigger authorization
if (accessToken == undefined){
var speechText = "You need to link your Account."+
"Follow the instructions"+
"on the screen or in your Alexa App.";
return handlerInput.responseBuilder
.speak(speechText)
.withLinkAccountCard()
.getResponse();
}
}
};

When this handler returns, the user needs to sign in on the login page of the third-party (e.g. Spotify) in the Alexa companion App and consent to the data sharing. The technical complexity of the OAuth flow is hidden from the Skill developer, as the redirect endpoint is provided by Alexa and the token endpoint gets called automatically by Alexa with the correct parameters. As a result, we get the access token in the user object of the next request:

handlerInput.requestEnvelope.context.System.user.accessToken

Check out the other posts in this series on Alexa Account Linking:

In my new book “Making Money with Alexa Skills – A Developer’s Guide” I describe not only how to develop, but also how to monetize Alexa Skills. Account linking is one of the possibilities for personalizing a Skill and make it unique – more practical approaches for personalizing Skills are described in the book. https://api-university.com/books/alexa

In the OAuth 2.0 book you can find a simple and understandable explanation of all the standard OAuth Flows (such as those supported by Alexa). What makes this book unique is that the complicated OAuth interactions are visualized as easy-to-understand Sequence Diagrams. https://api-university.com/books/oauth-2-0-book/

Part 3 of Alexa Account Linking with OAuth: Skill Service: Get Access Token

Also published on Medium.

Tagged on: