As the quest for an advanced Alexa AVS skill continues, all kinds of challenges cross my path. This time I encountered a problem that cost me quite some time to solve. While trying to have Alexa's account linking to work with the Salesforce Oauth Webserver flow, I needed a way to verify the access token issued by Salesforce and get information about the user in question, using APEX.

The problem

When implementing Alexa account linking, it's possible to authenticate the user with Salesforce. In my case, a community user. After linking the account, Alexa will send the access token with each of its requests to the REST endpoint. In my case, this REST endpoint is hosted on Salesforce and therefore ideally the token is validated using APEX. Along with the prescribed validation, one would want to obtain the associated user's information.

To validate the access token and obtain user data, I tried several approaches. The first attempt was to use SOQL on the OauthToken object, passing Alexa's token as the AccessToken or RequestToken where-clauses. This did not work. The tokens in the object appear to be obfuscated. Perhaps this would have worked using the SOAP API, but I didn't try this. An APEX SOQL query along these lines throws exceptions.

Then I realized I was making things too complicated, since there's also an Oauth endpoint that's not discussed or implemented a lot (judging from my adventures on Google to try and solve this challenge). This endpoint is located at /services/oauth2/userinfo. This endpoint may be called with a (Bearer) token and will return user information if the token is valid.

Thinking I had solved the problem, I quickly became disappointed. The userinfo endpoint kept returning "Bad_OAuth_Token" with a 403 status code. As usual, when I have no clue what's wrong, I ended up modifying all kinds of meta data on Salesforce. The connected app, the APEX code, the encoding of the token etc. etc. All to no avail.

The solution

After a night's sleep, I hit Google again. In desperation this time. Hours of Googling had had no result and on my new attempt, all the same links kept appearing, no matter what creative search term I came up with.

Then, reading the same Stack overflow topic for at least the 5th time, it dawned to me. I had been barking up the wrong tree completely! One tiny comment in this topic, made me realize I had to re-authorize the user!!

The token that I had been using all the time was quite old. It had been issued at the time the "openid" scope had not yet been defined in my configuration. Although I changed this later, the token was still working under the old scope, resulting in "Bad_OAuth_Token".

So I disabled the Alexa skill in my companion app. Re-enabling it fired the account linking dance again and a new token was issued. This time, the token was accepted by the userinfo endpoint and I got the user information I needed!