Invalid storage account when developing Azure Function in Visual Studio - c#

I'm developing Azure Function in Visual Studio using C#. And I'n running it locally on my development machine which sits behind a proxy. However keep getting this error:
Exception binding parameter Invalid storage account Please make sure your credentials are correct
In my C# class I have following function which have an output binding to a Service Bus queue.
[FunctionName("MyTestFunction")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, [Queue("myqueue")]IAsyncCollector<string> myQueue, TraceWriter log)
In local.settings.json, I populated AzureWebJobsStorage and AzureWebJobsDashboard with connection string copied from Azure Storage Explorer
{
"IsEncrypted": false,
"Values": {"AzureWebJobsStorage":"DefaultEndpointsProtocol=https;AccountName=storageaccountname;AccountKey=sNFYlzkTtIVejJqU36rhByzDq91Nyv+JQ==;BlobEndpoint=https://storageaccount.blob.core.windows.net/;QueueEndpoint=https://storageaccount.queue.core.windows.net/;TableEndpoint=https://storageaccount.table.core.windows.net/;FileEndpoint=https://storageaccount.file.core.windows.net/;",
"AzureWebJobsDashboard": "DefaultEndpointsProtocol=https;AccountName=storageaccountname;AccountKey=sNFYlzkTtIVejJqU36rhByzDq91Nyv+JQ==;BlobEndpoint=https://storageaccount.blob.core.windows.net/;QueueEndpoint=https://storageaccount.queue.core.windows.net/;TableEndpoint=https://storageaccount.table.core.windows.net/;FileEndpoint=https://storageaccount.file.core.windows.net/;"
}
}
It worked for me for a while, but then stopped working all together. I triple checked everything and still couldn't figure out what I did wrong. Can someone point me to the right direction for this please?
The value I have for AzureWebJobsStorage and AzureWebJobsDashboard are straight copy from the Primary Connection String of my storage account in Azure Storage Explorer.

I had a similar error message:
Missing storage secret credentials.
Following this document, I used the Azure Functions CLI (func.exe) (Command Line Interface) to update all necessary credentials in my local.settings.json.
Ensure you have node.js
Install Azure CLI if not already done so: npm install -g azure-functions-core-tools
In your Azure Functions v2 project root directory, execute func azure functionapp fetch-app-settings myawesomefunctionappname
You should see your credentials getting updated in local.settings.js. Local debugging might require you to have non-encrypted credentials. Simply set IsEncrypted: false in that file.
Here's a sample:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "DefaultEndpointsProtocol=https;AccountName=...",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"APPINSIGHTS_INSTRUMENTATIONKEY": "...",
"FUNCTIONS_EXTENSION_VERSION": "~2",
"WEBSITE_CONTENTAZUREFILECONNECTIONSTRING": "DefaultEndpointsProtocol=https;AccountName=...",
"WEBSITE_CONTENTSHARE": "...",
"WEBSITE_NODE_DEFAULT_VERSION": "8.11.1",
"WEBSITE_LOAD_CERTIFICATES": "*",
"WEBSITE_RUN_FROM_PACKAGE": "1"
},
"ConnectionStrings": {}
}

For those experiencing the same problem - developing Azure Functions locally (using Visual Studio) behind a proxy.
Here is how I fixed the issue - adding proxy settings in the func.exe.Config. You will be able to find the file under C:\Users\{yourAccountName}\AppData\Local\Azure.Functions.Cli\1.0.0\func.exe.Config
Add your proxy settings as:
<system.net>
<defaultProxy useDefaultCredentials="true">
<proxy usesystemdefault="True" proxyaddress="http://my.proxy.com:8080" bypassonlocal="True" autoDetect="True" />
</defaultProxy>
</system.net>
Hope this helps someone.
I really wish the error message returned actually tells us the CLI is actually not able to connect to Azure, rather than keep telling me I'm using an invalid storage account.

We were recently facing a similar issue with one of our web job which was working fine earlier but suddenly stopped working. Web job tried to restart every minute but it was getting failed with the error message Invalid storage account ABStorage. Please make sure your credentials are correct. Web job remained in Pending Restart status. Upon investigation, we found out that the storage connection string is perfectly fine while there is some bug in Azure storage SDK due to which CORS rules configured on Azure portal against the storage account were not being interpreted correctly. In the Azure portal, we had only 1 CORS rule on Azure storage having all allowed HTTP methods selected. We updated the CORS rule on the storage account to have one HTTP method per domain and the web job was able to start immediately.

Related

Is Azure storage supported in Azure Static Web App functions?

I'm working on an API for an Azure Static Web App. The web app is implemented in Angular (although that isn't important for this question), and the API is implemented in C# (NET 6). Deployment to Azure is via a GitHub action.
I can create an HTTP trigger API endpoint that works fine, like so:
public static class Tester
{
[FunctionName("Tester")]
public static IActionResult Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "v1/tester")] HttpRequest req,
ILogger log)
{
return new OkObjectResult("Hello World");
}
}
I'm also able to access this directly via the SWA URL: https://<sitename>.azurestaticapps.net/api/v1/tester.
However, as soon as I add a reference to an Azure storage NuGet package to the project file (specifically Microsoft.Azure.WebJobs.Extensions.Storage.Blobs), making no other changes to the code, the API endpoint no longer works once deployed (although it will work locally).
On deploying the code with that package referenced in the .csproj, hitting the API endpoint gives a 503 status code with the response:
Function host is not running.
I enabled Application Insights for this static web app, and a CryptographicException is being thrown on startup:
An error occurred while trying to encrypt the provided data. Refer to the inner exception for more information. For more information go to http://aka.ms/dataprotectionwarning Could not find any recognizable digits.
(The link in the message doesn't go anywhere useful).
I'm presuming this has something to do with the AzureWebJobsStorage setting, which cannot be set in an Azure Static Web App (for whatever reason).
Based on all of the above, it would seem that using Azure storage from within a static web app C# function is verboten. However, I can't find that stated explicitly online anywhere. Has anybody got this kind of thing to work?
I removed the following nuget packages to make it working:
Microsoft.Azure.EventGrid
Microsoft.Azure.WebJobs.Extensions.EventGrid
I decomposed my http functions to a separate project because SWA does not support the EventTriggers right now.

CORS Issue with Azure Functions inside AKS Cluster

I have a AKS Cluster in Azure which is running my Azure functions project. I got it working by following this guide.
https://markheath.net/post/azure-functions-aks-keda
The service is running, however any requests from my site fail with a CORS error. If you notice on the guide the CORS option is set to * in the local.settings.json file.
I noticed that azure functions does not seem to read the local.settings.json or settings.json files when running inside a container.
I am not sure why but to get it running locally I had to set the connection strings as environment variables.
It looks like the func kubernetetes deploy --dry-run > deploy.yml does the same, as the yaml looks something like this:
data:
AzureWebJobsStorage: ConnectionStringHere
AzureSignalRConnectionString: ConnectionStringHere
AzureBlobStorage: ConnectionStringHere
FUNCTIONS_WORKER_RUNTIME: ZG90bmV0
FUNCTIONS_V2_COMPATIBILITY_MODE: dHJ1ZQ==
apiVersion: v1
kind: Secret
metadata:
name: my-app-live
namespace: default
---
apiVersion: v1
Note, there is no reference to CORS in there at all, even against the LoadBalancer.
I have done some research and it looks like others change the load balancer to nginx as a reverse proxy to deal with this. I am not sure this an option for me or what the repercussions would be as this is using DurableFunctions and KEDA for scaling and I don't want to do anything that might break that functionality.
The FunctionApp is written in C#
I am very new to Kubernetes so please give as much detail as possible if you can help.

Disable Azure Function from C# for runtime version 3.x?

How can I disable an Azure Function using code in C#?
I'm using Azure Functions Runtime version 3.x
I'm implementing a distributed circuit-breaker inspired by Serverless circuit breakers with Durable Entities. When the circuit opens I need to disable a queue-trigged Azure Function, instead of stopping the entire function app.
I see from How to disable functions in Azure Functions that the recommended way to disable a function is to set the AzureWebJobs.<FUNCTION_NAME>.Disabled app setting. But I haven't found an API for doing that in C#. I'm hoping there is something that I can call from my C# code that is equivalent to the Azure CLI's az functionapp config appsettings set command.
I saw similar questions on SO like:
azure set environment variable programmatically to disable an azure function
and How to Enable/Disable Azure Function programmatically
But those have answers from back in 2017 that use kudu APIs to change the disabled property in the function.json file, and I'm hoping that there is a better way to do that now. Especially because the Docs at How to disable functions in Azure Functions say:
The generated function.json file for a class library function is not
meant to be edited directly. If you edit that file, whatever you do to
the disabled property will have no effect.
Unfortunately I was not able to find any documentation as such. The closest I got was
https://learn.microsoft.com/en-us/rest/api/appservice/webapps/createfunction
For instance to create the function :
https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/functions/{functionName}?api-version=2019-08-01
However this documentation also did not take me near to your requirement of updating the Config File. Or I may have overlooked few modules. Request you check further before implementing the below steps
So here's is what I did, I was kind of trying to reverse engineer, I ran the commands in Azure CLI and captured the traces - my thought process - the Azure CLI internally run on python and issues the API request to the Azure.
Ran the below command and captured Fiddler :
az functionapp config appsettings set --name <myFunctionApp> \
--resource-group <myResourceGroup> \
--settings AzureWebJobs.QueueTrigger.Disabled=true
And Yes ! The python process was issuing request to https://management.azure.com to update appsetting :
The set property is sent in the Request Body :
We can hardcode the properties or get it dynamically.
So I ran the below Azure CLI command
az functionapp config appsettings list --name <> --resource-group <>
I was able to see the above properties that was passed along the PUT request
Took the fiddler for the above command
Saw there is a POST Request to the below endpoint :
https://management.azure.com/subscriptions//resourceGroups//providers/Microsoft.Web/sites//config/appsettings/list?api-version=2019-08-01
These are the same set of property bags which are sent as the request bodies in the PUT in order to set the property.
So in your case you will have to request the above end point to get the list of properties. It is json output. Update the value of AzureWebJobs.QueueTrigger.Disabled to True.
Issue the Updated properties using the PUT method along with the headers such as Bearer Token & Content-Type: application/json; charset=utf-8
Request URI :
https://management.azure.com/subscriptions//resourceGroups//providers/Microsoft.Web/sites//config/appsettings?api-version=2019-08-01
Headers :
Authorization: Bearer <> Content-Type: application/json;
charset=utf-8`
Request Body:
{"kind": "<class 'str'>", "properties": }
I hope you will be able to achieve your requirement.
I hope this helps you :)
I don't recommend this for your prod. Pls try and monitor in your Dev env.

401 Unauthorized when querying durable function status

I need some help with Azure Durable Functions.
I created a new durable function with VS Code in C# and deployed it to Azure via the VS Code azure function extension. The function app resource was already created manually in the portal. I use
FUNCTIONS_WORKER_RUNTIME: dotnet
FUNCTIONS_EXTENSION_VERSION: ~2
I can trigger the creation of an durable task and but when I query the status with the statusQueryGetUri, I only get a 401 Unauthrized. The http trigger of the function itself is anonymous and does not require authentication (for debug purpose only).
The requests look like this (I used Postman to send the requests):
HTTP POST https://{function-app}.azurewebsites.net/api/SayHello_HttpStart
Response:
{
"id": "da3259a462084e86a34f8ce9859a6ed6",
"statusQueryGetUri": "https://{function-app}.azurewebsites.net/runtime/webhooks/durabletask/instances/da3259a462084e86a34f8ce9859a6ed6?taskHub=DurableFunctionsHub&connection=Storage&code=ua4tHacVv9JDH5phKCJI1OdKGXQSB/MMUX8WIv1E0OyZANqrRY3L/g==",
"sendEventPostUri": "https://{function-app}.azurewebsites.net/runtime/webhooks/durabletask/instances/da3259a462084e86a34f8ce9859a6ed6/raiseEvent/{eventName}?taskHub=DurableFunctionsHub&connection=Storage&code=ua4tHacVv9JDH5phKCJI1OdKGXQSB/MMUX8WIv1E0OyZANqrRY3L/g==",
"terminatePostUri": "https://{function-app}.azurewebsites.net/runtime/webhooks/durabletask/instances/da3259a462084e86a34f8ce9859a6ed6/terminate?reason={text}&taskHub=DurableFunctionsHub&connection=Storage&code=ua4tHacVv9JDH5phKCJI1OdKGXQSB/MMUX8WIv1E0OyZANqrRY3L/g==",
"rewindPostUri": "https://{function-app}.azurewebsites.net/runtime/webhooks/durabletask/instances/da3259a462084e86a34f8ce9859a6ed6/rewind?reason={text}&taskHub=DurableFunctionsHub&connection=Storage&code=ua4tHacVv9JDH5phKCJI1OdKGXQSB/MMUX8WIv1E0OyZANqrRY3L/g==",
"purgeHistoryDeleteUri": "https://{function-app}.azurewebsites.net/runtime/webhooks/durabletask/instances/da3259a462084e86a34f8ce9859a6ed6?taskHub=DurableFunctionsHub&connection=Storage&code=ua4tHacVv9JDH5phKCJI1OdKGXQSB/MMUX8WIv1E0OyZANqrRY3L/g=="
}
The Get Request is then simply:
GET https://{function-app}.azurewebsites.net/runtime/webhooks/durabletask/instances/da3259a462084e86a34f8ce9859a6ed6?taskHub=DurableFunctionsHub&connection=Storage&code=ua4tHacVv9JDH5phKCJI1OdKGXQSB/MMUX8WIv1E0OyZANqrRY3L/g==
Did I miss some configuration I have to set to allow access to the uri? What logs might help me figure out what the problem is?
When I run the code locally there are no problems and everything works as expected.
Thanks a lot for all help!
Note that the statusQueryGetUri is an admin endpoint which always requires a System Key.
GET <rootUrl>/runtime/webhooks/durabletask/instances/<GUID>
?taskHub={taskHub}
&connection={connection}
&code={systemKey}
As an alternative, you could also set the x-functions-key header of the http request with this key.
More info on the usage of the HTTP endpoints in the docs.

asp.net core 2.0 deployment - InvalidOperationException: The antiforgery token could not be decrypted

Recently I developed a asp.net core 2.0 web app in my company and in debug mode works perfect, however when I deployed in our testing server into IIS and we try to execute from a client machine it ran into a problem:
An unhandled exception occurred while processing the request.
CryptographicException: The key {0851ad3b-df33-4cf7-8c3a-5c637adaa713} was not found in the key ring.
Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore(Byte[] protectedData, bool allowOperationsOnRevokedKeys, out UnprotectStatus status)
InvalidOperationException: The antiforgery token could not be decrypted.
Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgeryTokenSerializer.Deserialize(string serializedToken)
The problem starts when I submmit login page. I investigated links with same problems here and other blogs, but I found that has to be with ValidateAntiForgeryToken and solution is related with Microsoft.AspNetCore.DataProtection. I added nuget package Microsoft.AspNetCore.DataProtection.Redis to my project and I added in ConfigureServices of startup class following code:
var redis = ConnectionMultiplexer.Connect("192.168.10.151:80");
services.AddDataProtection().PersistKeysToRedis(redis, "DataProtection-Keys");
services.AddOptions();
Our testing server ip is 192.168.10.151, however app throws following exception:
RedisConnectionException: It was not possible to connect to the redis server(s); to create a disconnected multiplexer, disable AbortOnConnectFail. InternalFailure on PING
¿Why it doesn't connect since is resolving in the same web app server?
¿Where is DataProtection-Keys database located?
as a workaround, I changed method by using PersistKeysToFileSystem as follows:
services.AddDataProtection()
.SetApplicationName("myapp-portal")
.PersistKeysToFileSystem(new System.IO.DirectoryInfo (#"c:\ProgramData\dpkeys"));
However running app in test server 192.168.10.151, when login form is submitted, goes back to login page. Checking stdout log file, only shows:
Hosting environment: Production
Content root path: C:\inetpub\wwwroot\OmniPays
Now listening on: http://localhost:30064
Application started. Press Ctrl+C to shut down.
Checking network messages by chrome's developers tools I noticed something:
Request URL: http://192.168.10.151/OmniPays/Account/Login
Request Method: POST
Status Code: 302 Found
Remote Address: 192.168.10.151:80
Referrer Policy: no-referrer-when-downgrade
and then ...
Request URL: http://192.168.10.151/OmniPays/Home/Main
Request Method: GET
Status Code: 302 Found
Remote Address: 192.168.10.151:80
Referrer Policy: no-referrer-when-downgrade
AccountController's Login action redirect request to HomeController's Main action only if authentication succeded, and Main action has [Authorize] attribute. For some reasons I can't achieve understand, Main action fails and return to Login page. URL in chrome shows: http://192.168.10.151/OmniPays/Account/Login?ReturnUrl=%2FOmniPays%2FHome%2FMain
I'm using Microsoft Identity. In debug mode works fine and if I deploy app in my local PC on IIS also works fine. ¿Maybe any SDK is missing in the server?
Please need help!!
Solution was found! the cause of problem was not in IIS neither the Server, connection to the server is using http rather than https, no certifies involved to validate secure connection, however testing in differents servers app works ok, so I felt really disappointed. Solution was to remove cookies an any data related with this URL pointing to Development Server (failing) in all browsers, data that was previously stored, and voila!!, now app works perfect. By default, as bhmahler comments data protection is made in memory and I left configuration by default, I mean, not explicitly persistence in redis nor PersistKeysToFileSystem and works fine, however is important to set DataProtection to strong data sensitive protection.
I'm newbie about these topics and It's unbelievable such a simple thing caused on me that waste of time. Thanks to all!.

Categories