Token request failed error when getting app only access token

Recently I started seeing token request failed error in my job and my provider hosted app.   The jobs and provided hosted apps have been working well for a long time and it just suddenly happened.  They always failed at TokenHelper.getAppOnlyAccessToken method.

Error info:

Type: System.Net.WebException

Message: Token request failed.

After digging around, it looks like there are a few updates on Microsoft to SharePoint, Azure, and AAD.  You can see more details from here, https://techcommunity.microsoft.com/t5/microsoft-sharepoint-blog/provider-hosted-app-pha-application-errors-tls-errors-and-401/ba-p/2273611.

Essentially, here are the 2 solution depending where is your code located:

  • If you're running your jobs or web applications on a server, you can apply the change to update the TLS and cipher used.  See the details for the TLS/Cipher changes in the link above.
  • If you're hosting the provided hosted app in Azure web app, you can update your code instead.  You can add ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 to your code before you get the AppOnly access token.
Sample code:


public ClientContext GetAppContext() 
{
    ServicePointManager.SecurityPortocol = SecurityProtocolType.Tls12;
    Uri siteUri = new Uri(_sharepointUrl);    
    string realm = TokenHelper.GetRealmFromTargetUrl(siteUri);

    string accessToken = TokenHelper.GetAppOnlyAccessToken(
        TokeHelper.SharePointPrincipal, 
        siteUri.Authority, realm).AccessToken;

    return TokenHelper.GetClientContextWithAccessToken(siteUri.ToString(), accessToken);
}

after I added the yellow highlighted line, it started working on Azure web app.  That force the code to use TLS 1.2.

Comments

Popular posts from this blog

SharePoint 2013 App Details Page Error

SharePoint 2013 - Working with Display Template for Content Search Web Part

Add spell check dictionary in SharePoint 2010, SharePoint 2013, and Office 365