pnpframework icon indicating copy to clipboard operation
pnpframework copied to clipboard

Azure Function App received an error - The remote server returned an error /(401) Unauthorized.

Open bongsooseo opened this issue 2 years ago • 1 comments

Category

  • [x] Bug

Describe the bug

When we use an Azure Function App to get an access token from SharePoint (App only) Authentication, we received 401 error. However, when we test it locally in VS code and postman, curl command in Function App kudu site, it all works well. In addition, the ApplicationID and AppSecret are correct.

Please look at the "Additional Details" for the error. Here is some code for communicating to sharePoint site.

public async static Task<ClientContext> GetClientContext(string siteUrl, ExecutionContext context, ILogger log) { await Task.CompletedTask;

        var config = new ConfigurationBuilder()
            .SetBasePath(context.FunctionAppDirectory)
            .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
            .AddEnvironmentVariables().Build();
			
        string applicationID = config["applicationID"] == string.Empty ? string.Empty : config["applicationID"];
        string AppSecret = config["AppSecret"] == string.Empty ? string.Empty : config["AppSecret"];
        
        if(string.IsNullOrEmpty(applicationID)){
            applicationID = Environment.GetEnvironmentVariable("applicationID");
        }
        if(string.IsNullOrEmpty(AppSecret)){
            AppSecret = Environment.GetEnvironmentVariable("AppSecret");
        }

        log.LogInformation("SPOAuthHelper >> GetClientContext >> Url: [" + siteUrl + "]");
        log.LogInformation("SPOAuthHelper >> GetClientContext >> AppID: [" + applicationID + "]");
        log.LogInformation("SPOAuthHelper >> GetClientContext >> AppSecret: [" + AppSecret + "]");

        ClientContext ctx = new PnP.Framework.AuthenticationManager().GetACSAppOnlyContext(siteUrl, applicationID, AppSecret);

        return ctx;

    }

In addition, please take a look at the detail information below.

  • SDK version: PnP.Core" Version="1.9.0 and PnP.Framework" Version="1.12.0
  • OS: Windows
  • SDK used in: .NET Azure Function App
  • Framework: .NET 6
  • Additional details:

Full Exception : Exception while executing function /TaxDMSFnSPO_Admin ---> System.Exception /Token request failed. ---> System.Net.WebException /The remote server returned an error /(401) Unauthorized.

System.Net.HttpWebRequest.GetResponse()

SharePointPnP.IdentityModel.Extensions.S2S.Protocols.OAuth2.OAuth2WebRequest.GetResponse()

SharePointPnP.IdentityModel.Extensions.S2S.Protocols.OAuth2.OAuth2S2SClient.Issue(String securityTokenServiceUrl,OAuth2AccessTokenRequest oauth2Request) End of inner exception

SharePointPnP.IdentityModel.Extensions.S2S.Protocols.OAuth2.OAuth2S2SClient.Issue(String securityTokenServiceUrl,OAuth2AccessTokenRequest oauth2Request)

PnP.Framework.Utilities.TokenHelper.GetAppOnlyAccessToken(String targetPrincipalName,String targetHost,String targetRealm)

PnP.Framework.Utilities.ACSTokenGenerator.GetToken(Uri siteUrl)

PnP.Framework.AuthenticationManager.<GetContextAsync>b__62_0(String site)

PnP.Framework.AuthenticationManager.<>c__DisplayClass78_0.<GetAccessTokenContext>b__0(Object sender,WebRequestEventArgs args)

Microsoft.SharePoint.Client.ClientRuntimeContext.OnExecutingWebRequest(WebRequestEventArgs args)

Microsoft.SharePoint.Client.ClientRequest.SetupServerQuery(ChunkStringBuilder sb)

Microsoft.SharePoint.Client.ClientRequest.ExecuteQueryToServer(ChunkStringBuilder sb)

Microsoft.SharePoint.Client.ClientContext.ExecuteQuery()

TaxDMS.Function.AdminPermissionCheck.AdminPermissionCheckRun(String HubSiteURL,String AuthorityString,String ResourceString,X509Certificate2 certValue,IQueryCollection reqQuery,Object data,ExecutionContext context,GetResultEntity& entities,Boolean isDebug,Boolean isTest,ILogger log) D:\a\1\s\Process\AdminPermissionCheck.cs /38

CallSite.Target(Closure ,CallSite ,AdminPermissionCheck ,String ,String ,String ,X509Certificate2 ,IQueryCollection ,Object ,ExecutionContext ,GetResultEntity& ,Boolean ,Boolean ,ILogger )

async TaxDMS.Function.TaxDMSFnSPO_Admin.Run(HttpRequest req,ExecutionContext context,ILogger log) D:\a\1\s\TaxDMSFnSPO_Admin.cs /150

System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

async Microsoft.Azure.WebJobs.Host.Executors.FunctionInvoker`2.InvokeAsync[TReflected,TReturnValue](Object instance,Object[] arguments) D:\a_work\1\s\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionInvoker.cs /52

System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.InvokeWithTimeoutAsync(IFunctionInvoker invoker,ParameterHelper parameterHelper,CancellationTokenSource timeoutTokenSource,CancellationTokenSource functionCancellationTokenSource,Boolean throwOnTimeout,TimeSpan timerInterval,IFunctionInstance instance) D:\a_work\1\s\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs /581

System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithWatchersAsync(IFunctionInstanceEx instance,ParameterHelper parameterHelper,ILogger logger,CancellationTokenSource functionCancellationTokenSource) D:\a_work\1\s\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs /527

System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(IFunctionInstanceEx instance,FunctionStartedMessage message,FunctionInstanceLogEntry instanceLogEntry,ParameterHelper parameterHelper,ILogger logger,CancellationToken cancellationToken) D:\a_work\1\s\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs /306 End of inner exception

System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(IFunctionInstanceEx instance,FunctionStartedMessage message,FunctionInstanceLogEntry instanceLogEntry,ParameterHelper parameterHelper,ILogger logger,CancellationToken cancellationToken) D:\a_work\1\s\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs /352

System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.TryExecuteAsync(IFunctionInstance functionInstance,CancellationToken cancellationToken) D:\a_work\1\s\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs /108

bongsooseo avatar Sep 22 '23 07:09 bongsooseo

Any ETA on the update/fix for the issue. @bongsooseo are you using any alternative for now.

codejunction avatar Dec 18 '23 08:12 codejunction