title: Not able to run an Azure Web Job Error: Microsoft.IdentityModel.SecurityTokenService.RequestFailedException: Token request failed
body: <p>We have an Azure Web Job that runs weekly. But of late it has not been running. When we checked the  logs this is what we get</p>
  
  <pre><code>    [04/28/2017 16:32:38 &gt; e85929: SYS INFO] Status changed to Initializing
  
  [04/28/2017 16:32:40 &gt; e85929: SYS INFO] Run script 'EmailSchedulerJob.exe' with script host - 'WindowsScriptHost'
  
  [04/28/2017 16:32:40 &gt; e85929: SYS INFO] Status changed to Running
  
  [04/28/2017 16:32:40 &gt; e85929: INFO] Site URL is https://name.sharepoint.com
  
  [04/28/2017 16:32:41 &gt; e85929: INFO] Error: Microsoft.IdentityModel.SecurityTokenService.RequestFailedException: Token request failed. ---&gt; System.Net.WebException: The remote server returned an error: (401) Unauthorized.
  
  [04/28/2017 16:32:41 &gt; e85929: INFO]    at System.Net.HttpWebRequest.GetResponse()
  
  [04/28/2017 16:32:41 &gt; e85929: INFO]    at Microsoft.IdentityModel.S2S.Protocols.OAuth2.OAuth2WebRequest.GetResponse()
  
  [04/28/2017 16:32:41 &gt; e85929: INFO]    at Microsoft.IdentityModel.S2S.Protocols.OAuth2.OAuth2S2SClient.Issue(String securityTokenServiceUrl, OAuth2AccessTokenRequest oauth2Request)
  
  [04/28/2017 16:32:41 &gt; e85929: INFO]    --- End of inner exception stack trace ---
  
  [04/28/2017 16:32:41 &gt; e85929: INFO]    at Microsoft.IdentityModel.S2S.Protocols.OAuth2.OAuth2S2SClient.Issue(String securityTokenServiceUrl, OAuth2AccessTokenRequest oauth2Request)
  
  [04/28/2017 16:32:41 &gt; e85929: INFO]    at EmailSchedulerJob.TokenHelper.GetAppOnlyAccessToken(String targetPrincipalName, String targetHost, String targetRealm)
  
  [04/28/2017 16:32:41 &gt; e85929: INFO]    at EmailSchedulerJob.Program.Main(String[] args)
  
  [04/28/2017 16:32:41 &gt; e85929: SYS INFO] Status changed to Success
  </code></pre>
  
  <p>I thought it was something to do with the code. We published multiple versions of this project but still getting the same Issue. The code performs a lookup on a SharePoint list.</p>
  
  <p>We also tried looking at the Publish Settings file. It appears to be slightly different with a link to the Control Panel</p>
  
  <pre><code>&lt;publishData&gt;&lt;publishProfile profileName="TestAppName - Web Deploy" publishMethod="MSDeploy" publishUrl="testappname.scm.azurewebsites.net:443" msdeploySite="estAppName" userName="$TestAppName" userPWD="" destinationAppUrl="http://appname.azurewebsites.net" SQLServerDBConnectionString="" mySQLDBConnectionString="" hostingProviderForumLink="" controlPanelLink="http://windows.azure.com" webSystem="WebSites"&gt;&lt;databases /&gt;&lt;/publishProfile&gt;&lt;publishProfile profileName="TestAppName - FTP" publishMethod="FTP" publishUrl="ftp://waws-prod-sn1-031.ftp.azurewebsites.windows.net/site/wwwroot" ftpPassiveMode="True" userName="TestAppName\$TestAppName" userPWD="" destinationAppUrl="http://testappname.azurewebsites.net" SQLServerDBConnectionString="" mySQLDBConnectionString="" hostingProviderForumLink="" controlPanelLink="http://windows.azure.com" webSystem="WebSites"&gt;&lt;databases /&gt;&lt;/publishProfile&gt;&lt;/publishData&gt;
  </code></pre>
  
  <p>Any suggestions on how this can be resolved would be greatly appreciated.</p>
  
  <p><strong>EDIT:</strong>
  Code for Initializing the web job
  webjob-publish-settings.json</p>
  
  <pre><code>{
    "$schema": "http://schemastore.org/schemas/json/webjob-publish-settings.json",
    "webJobName": "EmailSchedulerJob",
    "startTime": "2016-05-30T00:00:00-05:00",
    "endTime": null,
    "jobRecurrenceFrequency": "Week",
    "interval": 1,
    "runMode": "Scheduled"
  }
  </code></pre>
  
  <p>web.config file</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;!--
    For more information on how to configure your ASP.NET application, please visit
    http://go.microsoft.com/fwlink/?LinkId=169433
    --&gt;
  &lt;configuration&gt;
    &lt;system.web&gt;
      &lt;compilation debug="true" targetFramework="4.5"/&gt;
      &lt;httpRuntime targetFramework="4.5"/&gt;
    &lt;/system.web&gt;
    &lt;appSettings&gt;
      &lt;add key="ClientId" value=""/&gt;
      &lt;add key="ClientSecret" value=""/&gt;
      &lt;add key="DaysLeftToRemind" value="3"/&gt;
    &lt;/appSettings&gt;
    &lt;system.serviceModel&gt;
      &lt;bindings&gt;
        &lt;basicHttpBinding&gt;
          &lt;!--Used by SharePoint Add-in--&gt;
          &lt;binding name="secureBinding"&gt;
            &lt;security mode="Transport"/&gt;
          &lt;/binding&gt;
        &lt;/basicHttpBinding&gt;
      &lt;/bindings&gt;
      &lt;protocolMapping&gt;
        &lt;add binding="basicHttpBinding" scheme="https" bindingConfiguration="secureBinding"/&gt;
      &lt;/protocolMapping&gt;
    &lt;/system.serviceModel&gt;
    &lt;system.codedom&gt;
      &lt;compilers&gt;
        &lt;compiler language="c#;cs;csharp" extension=".cs"
          type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
          warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/&gt;
        &lt;compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
          type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
          warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&amp;quot;Web\&amp;quot; /optionInfer+"/&gt;
      &lt;/compilers&gt;
    &lt;/system.codedom&gt;
  
  &lt;system.diagnostics&gt;
      &lt;sources&gt;
        &lt;source name="System.Net" tracemode="includehex" maxdatasize="1024"&gt;
          &lt;listeners&gt;
            &lt;add name="System.Net"/&gt;
          &lt;/listeners&gt;
        &lt;/source&gt;
        &lt;source name="System.Net.Sockets"&gt;
          &lt;listeners&gt;
            &lt;add name="System.Net"/&gt;
          &lt;/listeners&gt;
        &lt;/source&gt;
        &lt;source name="System.Net.Cache"&gt;
          &lt;listeners&gt;
            &lt;add name="System.Net"/&gt;
          &lt;/listeners&gt;
        &lt;/source&gt;
      &lt;/sources&gt;
      &lt;switches&gt;
        &lt;add name="System.Net" value="Verbose"/&gt;
        &lt;add name="System.Net.Sockets" value="Verbose"/&gt;
        &lt;add name="System.Net.Cache" value="Verbose"/&gt;
      &lt;/switches&gt;
      &lt;sharedListeners&gt;
        &lt;add name="System.Net"
          type="System.Diagnostics.TextWriterTraceListener"
          initializeData="D:\home\LogFiles\NetTracing\network.log"
             traceOutputOptions="ProcessId, DateTime"
        /&gt;
      &lt;/sharedListeners&gt;
      &lt;trace autoflush="true"/&gt;
    &lt;/system.diagnostics&gt;
  &lt;/configuration&gt;
  </code></pre>
  
  <p>Code for connecting to SharePoint</p>
  
  <pre><code>string sharepointSiteUrl = ConfigurationManager.AppSettings.Get("SPSiteUrl");
                  string emailUserName = ConfigurationManager.AppSettings.Get("EmailUserName"); 
                  string emailPassword = ConfigurationManager.AppSettings.Get("EmailPassword");
                  Uri sharepointSiteUri = new Uri(sharepointSiteUrl);
  
                  Console.WriteLine("Site URL is " + sharepointSiteUrl);
  
                  string appRealm = TokenHelper.GetRealmFromTargetUrl(sharepointSiteUri);
                  string accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, sharepointSiteUri.Authority, appRealm).AccessToken;
  </code></pre>
  
  <p><strong>Update</strong></p>
  
  <p>Since there is a possibility that the Client Secret Key might have expired we generated a new key and now when we run the Web Job we get this error on the logs-
   <strong>Error: Microsoft.SharePoint.Client.ServerUnauthorizedAccessException: Access denied. You do not have permission to perform this action or access this resource.</strong></p>
  
  <p>Current Log File</p>
  
  <pre><code>[05/01/2017 20:07:19 &gt; 56e469: SYS INFO] Status changed to Initializing
  
      [05/01/2017 20:07:19 &gt; 56e469: SYS INFO] Run script 'EmailSchedulerJob.exe' with script host - 'WindowsScriptHost'
  
      [05/01/2017 20:07:19 &gt; 56e469: SYS INFO] Status changed to Running
  
      [05/01/2017 20:07:20 &gt; 56e469: INFO] Site URL is https://sohodragon.sharepoint.com
  
      [05/01/2017 20:07:20 &gt; 56e469: INFO] Inside hostClientContext
  
      [05/01/2017 20:07:21 &gt; 56e469: INFO] Error: Microsoft.SharePoint.Client.ServerUnauthorizedAccessException: Access denied. You do not have permission to perform this action or access this resource.
  
      [05/01/2017 20:07:21 &gt; 56e469: INFO]    at Microsoft.SharePoint.Client.ClientRequest.ProcessResponseStream(Stream responseStream)
  
      [05/01/2017 20:07:21 &gt; 56e469: INFO]    at Microsoft.SharePoint.Client.ClientRequest.ProcessResponse()
  
      [05/01/2017 20:07:21 &gt; 56e469: INFO]    at Microsoft.SharePoint.Client.ClientRequest.ExecuteQueryToServer(ChunkStringBuilder sb)
  
      [05/01/2017 20:07:21 &gt; 56e469: INFO]    at Microsoft.SharePoint.Client.ClientRequest.ExecuteQuery()
  
      [05/01/2017 20:07:21 &gt; 56e469: INFO]    at Microsoft.SharePoint.Client.ClientRuntimeContext.ExecuteQuery()
  
      [05/01/2017 20:07:21 &gt; 56e469: INFO]    at Microsoft.SharePoint.Client.ClientContext.ExecuteQuery()
  
      [05/01/2017 20:07:21 &gt; 56e469: INFO]    at EmailSchedulerCommon.Code.Helpers.SharePointHelpers.GetListItemsByViewName(ClientContext ctx, String listName, String viewName)
  
      [05/01/2017 20:07:21 &gt; 56e469: INFO]    at EmailSchedulerCommon.Code.Business.HolidayManager.GetUpcomingHolidays(ClientContext ctx)
  
      [05/01/2017 20:07:21 &gt; 56e469: INFO]    at EmailSchedulerJob.Program.Main(String[] args)
  
  [05/01/2017 20:07:21 &gt; 56e469: SYS INFO] Status changed to Success
  </code></pre>