SharePoint App and “Invalid JWT token” exception

Let’s say you have a SharePoint App deployed on SharePoint Online, in Microsoft Office 365, and working since many months ago. Suddenly, it stops working and when you try to access it, you get back an exception like this:

System.IdentityModel.Tokens.SecurityTokenException: Invalid JWT token. Could not resolve issuer token.

That’s what happened to me today (I know, I’m a lucky boy!). Well, first of all I inspected the OAuth protocol flow using Fiddler and the Fiddler Extension for SharePoint App Token, which is available thanks to Kirk Evans. Thus, I noticed that in the SharePoint App Token of the failing app there was a difference, if compared with the App Token of a working app.

Here you can see the trailer of the token issued by ACS for the failing app:

{“typ”:”JWT”,“alg”:”RS256″,”x5t”:”kriMPdmBvx68skT8-mPAB3BseeA”}{“aud”:”a683fa34-b747-48cd-adc8-bfca2778684b/myfailingapp.azurewebsites.net@7f86dcab-5543-431d-a979-f5b7cd4912df”,”iss”:”00000001-0000-0000-c000-000000000000@7f86dcab-5543-431d-a979-f5b7cd4912df”, …. }

And, here you can see the trailer of a token issued by ACS for a good one:

{“typ”:”JWT”,“alg”:”HS256″}{“aud”:”912c71d7-6525-4b22-a6c2-01d3fd1bdd77/myworkingapp.azurewebsites.net@7f86dcab-5543-431d-a979-f5b7cd4912df”,”iss”:”00000001-0000-0000-c000-000000000000@7f86dcab-5543-431d-a979-f5b7cd4912df”,….}

Well, can you see the difference? Of course, the failing app receives a JWT token that is signed using an X.509 certificate and the RSA with SHA-256 algorithm. The x5t header parameter provides the encoded value of the thumbprint of the X.509 certificate used. While the good app uses an HMAC SHA-256 algorithm, instead.

And so what about the issue? After discussing with some of my friends and colleagues of the deceased 🙂 MC(S)M community, it came out that a Shared Secret of an app expires one year after the creation, and you have to renew it manually. Thanks to Oliver Zeiser and Neil Hodgkinson (@nellymo) I got a link to an article on MSDN, which explains exactly how to renew a Shared Secret for an app, without changing the Client ID. Here is the URL of the article “How to: Replace an expiring client secret in an app for SharePoint”: http://msdn.microsoft.com/en-us/library/office/dn726681(v=office.15).aspx

And by applying what is illustrated there, everyone lived happily ever after! 🙂

In case you will have the same kind of issue, I hope this blog post will help you solve it quickly, correlating the error message with the solution. Enjoy!